VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/ApplianceImplImport.cpp@ 45227

Last change on this file since 45227 was 45227, checked in by vboxsync, 12 years ago

Main: OVF 2.0 support. Part 1 - SHA256 digest is supported.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 124.0 KB
Line 
1/* $Id: ApplianceImplImport.cpp 45227 2013-03-28 12:22:11Z vboxsync $ */
2/** @file
3 *
4 * IAppliance and IVirtualSystem COM class implementations.
5 */
6
7/*
8 * Copyright (C) 2008-2013 Oracle Corporation
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.215389.xyz. 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#include <iprt/tar.h>
26#include <iprt/stream.h>
27
28#include <VBox/vd.h>
29#include <VBox/com/array.h>
30
31#include "ApplianceImpl.h"
32#include "VirtualBoxImpl.h"
33#include "GuestOSTypeImpl.h"
34#include "ProgressImpl.h"
35#include "MachineImpl.h"
36#include "MediumImpl.h"
37#include "MediumFormatImpl.h"
38#include "SystemPropertiesImpl.h"
39#include "HostImpl.h"
40
41#include "AutoCaller.h"
42#include "Logging.h"
43
44#include "ApplianceImplPrivate.h"
45
46#include <VBox/param.h>
47#include <VBox/version.h>
48#include <VBox/settings.h>
49
50using namespace std;
51
52////////////////////////////////////////////////////////////////////////////////
53//
54// IAppliance public methods
55//
56////////////////////////////////////////////////////////////////////////////////
57
58/**
59 * Public method implementation. This opens the OVF with ovfreader.cpp.
60 * Thread implementation is in Appliance::readImpl().
61 *
62 * @param path
63 * @return
64 */
65STDMETHODIMP Appliance::Read(IN_BSTR path, IProgress **aProgress)
66{
67 if (!path) return E_POINTER;
68 CheckComArgOutPointerValid(aProgress);
69
70 AutoCaller autoCaller(this);
71 if (FAILED(autoCaller.rc())) return autoCaller.rc();
72
73 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
74
75 if (!isApplianceIdle())
76 return E_ACCESSDENIED;
77
78 if (m->pReader)
79 {
80 delete m->pReader;
81 m->pReader = NULL;
82 }
83
84 // see if we can handle this file; for now we insist it has an ovf/ova extension
85 Utf8Str strPath (path);
86 if (!( strPath.endsWith(".ovf", Utf8Str::CaseInsensitive)
87 || strPath.endsWith(".ova", Utf8Str::CaseInsensitive)))
88 return setError(VBOX_E_FILE_ERROR,
89 tr("Appliance file must have .ovf extension"));
90
91 ComObjPtr<Progress> progress;
92 HRESULT rc = S_OK;
93 try
94 {
95 /* Parse all necessary info out of the URI */
96 parseURI(strPath, m->locInfo);
97 rc = readImpl(m->locInfo, progress);
98 }
99 catch (HRESULT aRC)
100 {
101 rc = aRC;
102 }
103
104 if (SUCCEEDED(rc))
105 /* Return progress to the caller */
106 progress.queryInterfaceTo(aProgress);
107
108 return S_OK;
109}
110
111/**
112 * Public method implementation. This looks at the output of ovfreader.cpp and creates
113 * VirtualSystemDescription instances.
114 * @return
115 */
116STDMETHODIMP Appliance::Interpret()
117{
118 // @todo:
119 // - don't use COM methods but the methods directly (faster, but needs appropriate locking of that objects itself (s. HardDisk))
120 // - Appropriate handle errors like not supported file formats
121 AutoCaller autoCaller(this);
122 if (FAILED(autoCaller.rc())) return autoCaller.rc();
123
124 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
125
126 if (!isApplianceIdle())
127 return E_ACCESSDENIED;
128
129 HRESULT rc = S_OK;
130
131 /* Clear any previous virtual system descriptions */
132 m->virtualSystemDescriptions.clear();
133
134 if (!m->pReader)
135 return setError(E_FAIL,
136 tr("Cannot interpret appliance without reading it first (call read() before interpret())"));
137
138 // Change the appliance state so we can safely leave the lock while doing time-consuming
139 // disk imports; also the below method calls do all kinds of locking which conflicts with
140 // the appliance object lock
141 m->state = Data::ApplianceImporting;
142 alock.release();
143
144 /* Try/catch so we can clean up on error */
145 try
146 {
147 list<ovf::VirtualSystem>::const_iterator it;
148 /* Iterate through all virtual systems */
149 for (it = m->pReader->m_llVirtualSystems.begin();
150 it != m->pReader->m_llVirtualSystems.end();
151 ++it)
152 {
153 const ovf::VirtualSystem &vsysThis = *it;
154
155 ComObjPtr<VirtualSystemDescription> pNewDesc;
156 rc = pNewDesc.createObject();
157 if (FAILED(rc)) throw rc;
158 rc = pNewDesc->init();
159 if (FAILED(rc)) throw rc;
160
161 // if the virtual system in OVF had a <vbox:Machine> element, have the
162 // VirtualBox settings code parse that XML now
163 if (vsysThis.pelmVboxMachine)
164 pNewDesc->importVboxMachineXML(*vsysThis.pelmVboxMachine);
165
166 // Guest OS type
167 // This is taken from one of three places, in this order:
168 Utf8Str strOsTypeVBox;
169 Utf8StrFmt strCIMOSType("%RU32", (uint32_t)vsysThis.cimos);
170 // 1) If there is a <vbox:Machine>, then use the type from there.
171 if ( vsysThis.pelmVboxMachine
172 && pNewDesc->m->pConfig->machineUserData.strOsType.isNotEmpty()
173 )
174 strOsTypeVBox = pNewDesc->m->pConfig->machineUserData.strOsType;
175 // 2) Otherwise, if there is OperatingSystemSection/vbox:OSType, use that one.
176 else if (vsysThis.strTypeVbox.isNotEmpty()) // OVFReader has found vbox:OSType
177 strOsTypeVBox = vsysThis.strTypeVbox;
178 // 3) Otherwise, make a best guess what the vbox type is from the OVF (CIM) OS type.
179 else
180 convertCIMOSType2VBoxOSType(strOsTypeVBox, vsysThis.cimos, vsysThis.strCimosDesc);
181 pNewDesc->addEntry(VirtualSystemDescriptionType_OS,
182 "",
183 strCIMOSType,
184 strOsTypeVBox);
185
186 /* VM name */
187 Utf8Str nameVBox;
188 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
189 if ( vsysThis.pelmVboxMachine
190 && pNewDesc->m->pConfig->machineUserData.strName.isNotEmpty())
191 nameVBox = pNewDesc->m->pConfig->machineUserData.strName;
192 else
193 nameVBox = vsysThis.strName;
194 /* If there isn't any name specified create a default one out
195 * of the OS type */
196 if (nameVBox.isEmpty())
197 nameVBox = strOsTypeVBox;
198 searchUniqueVMName(nameVBox);
199 pNewDesc->addEntry(VirtualSystemDescriptionType_Name,
200 "",
201 vsysThis.strName,
202 nameVBox);
203
204 /* Based on the VM name, create a target machine path. */
205 Bstr bstrMachineFilename;
206 rc = mVirtualBox->ComposeMachineFilename(Bstr(nameVBox).raw(),
207 NULL /* aGroup */,
208 NULL /* aCreateFlags */,
209 NULL /* aBaseFolder */,
210 bstrMachineFilename.asOutParam());
211 if (FAILED(rc)) throw rc;
212 /* Determine the machine folder from that */
213 Utf8Str strMachineFolder = Utf8Str(bstrMachineFilename).stripFilename();
214
215 /* VM Product */
216 if (!vsysThis.strProduct.isEmpty())
217 pNewDesc->addEntry(VirtualSystemDescriptionType_Product,
218 "",
219 vsysThis.strProduct,
220 vsysThis.strProduct);
221
222 /* VM Vendor */
223 if (!vsysThis.strVendor.isEmpty())
224 pNewDesc->addEntry(VirtualSystemDescriptionType_Vendor,
225 "",
226 vsysThis.strVendor,
227 vsysThis.strVendor);
228
229 /* VM Version */
230 if (!vsysThis.strVersion.isEmpty())
231 pNewDesc->addEntry(VirtualSystemDescriptionType_Version,
232 "",
233 vsysThis.strVersion,
234 vsysThis.strVersion);
235
236 /* VM ProductUrl */
237 if (!vsysThis.strProductUrl.isEmpty())
238 pNewDesc->addEntry(VirtualSystemDescriptionType_ProductUrl,
239 "",
240 vsysThis.strProductUrl,
241 vsysThis.strProductUrl);
242
243 /* VM VendorUrl */
244 if (!vsysThis.strVendorUrl.isEmpty())
245 pNewDesc->addEntry(VirtualSystemDescriptionType_VendorUrl,
246 "",
247 vsysThis.strVendorUrl,
248 vsysThis.strVendorUrl);
249
250 /* VM description */
251 if (!vsysThis.strDescription.isEmpty())
252 pNewDesc->addEntry(VirtualSystemDescriptionType_Description,
253 "",
254 vsysThis.strDescription,
255 vsysThis.strDescription);
256
257 /* VM license */
258 if (!vsysThis.strLicenseText.isEmpty())
259 pNewDesc->addEntry(VirtualSystemDescriptionType_License,
260 "",
261 vsysThis.strLicenseText,
262 vsysThis.strLicenseText);
263
264 /* Now that we know the OS type, get our internal defaults based on that. */
265 ComPtr<IGuestOSType> pGuestOSType;
266 rc = mVirtualBox->GetGuestOSType(Bstr(strOsTypeVBox).raw(), pGuestOSType.asOutParam());
267 if (FAILED(rc)) throw rc;
268
269 /* CPU count */
270 ULONG cpuCountVBox;
271 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
272 if ( vsysThis.pelmVboxMachine
273 && pNewDesc->m->pConfig->hardwareMachine.cCPUs)
274 cpuCountVBox = pNewDesc->m->pConfig->hardwareMachine.cCPUs;
275 else
276 cpuCountVBox = vsysThis.cCPUs;
277 /* Check for the constraints */
278 if (cpuCountVBox > SchemaDefs::MaxCPUCount)
279 {
280 addWarning(tr("The virtual system \"%s\" claims support for %u CPU's, but VirtualBox has support for max %u CPU's only."),
281 vsysThis.strName.c_str(), cpuCountVBox, SchemaDefs::MaxCPUCount);
282 cpuCountVBox = SchemaDefs::MaxCPUCount;
283 }
284 if (vsysThis.cCPUs == 0)
285 cpuCountVBox = 1;
286 pNewDesc->addEntry(VirtualSystemDescriptionType_CPU,
287 "",
288 Utf8StrFmt("%RU32", (uint32_t)vsysThis.cCPUs),
289 Utf8StrFmt("%RU32", (uint32_t)cpuCountVBox));
290
291 /* RAM */
292 uint64_t ullMemSizeVBox;
293 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
294 if ( vsysThis.pelmVboxMachine
295 && pNewDesc->m->pConfig->hardwareMachine.ulMemorySizeMB)
296 ullMemSizeVBox = pNewDesc->m->pConfig->hardwareMachine.ulMemorySizeMB;
297 else
298 ullMemSizeVBox = vsysThis.ullMemorySize / _1M;
299 /* Check for the constraints */
300 if ( ullMemSizeVBox != 0
301 && ( ullMemSizeVBox < MM_RAM_MIN_IN_MB
302 || ullMemSizeVBox > MM_RAM_MAX_IN_MB
303 )
304 )
305 {
306 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."),
307 vsysThis.strName.c_str(), ullMemSizeVBox, MM_RAM_MIN_IN_MB, MM_RAM_MAX_IN_MB);
308 ullMemSizeVBox = RT_MIN(RT_MAX(ullMemSizeVBox, MM_RAM_MIN_IN_MB), MM_RAM_MAX_IN_MB);
309 }
310 if (vsysThis.ullMemorySize == 0)
311 {
312 /* If the RAM of the OVF is zero, use our predefined values */
313 ULONG memSizeVBox2;
314 rc = pGuestOSType->COMGETTER(RecommendedRAM)(&memSizeVBox2);
315 if (FAILED(rc)) throw rc;
316 /* VBox stores that in MByte */
317 ullMemSizeVBox = (uint64_t)memSizeVBox2;
318 }
319 pNewDesc->addEntry(VirtualSystemDescriptionType_Memory,
320 "",
321 Utf8StrFmt("%RU64", (uint64_t)vsysThis.ullMemorySize),
322 Utf8StrFmt("%RU64", (uint64_t)ullMemSizeVBox));
323
324 /* Audio */
325 Utf8Str strSoundCard;
326 Utf8Str strSoundCardOrig;
327 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
328 if ( vsysThis.pelmVboxMachine
329 && pNewDesc->m->pConfig->hardwareMachine.audioAdapter.fEnabled)
330 strSoundCard = Utf8StrFmt("%RU32", (uint32_t)pNewDesc->m->pConfig->hardwareMachine.audioAdapter.controllerType);
331 else if (vsysThis.strSoundCardType.isNotEmpty())
332 {
333 /* Set the AC97 always for the simple OVF case.
334 * @todo: figure out the hardware which could be possible */
335 strSoundCard = Utf8StrFmt("%RU32", (uint32_t)AudioControllerType_AC97);
336 strSoundCardOrig = vsysThis.strSoundCardType;
337 }
338 if (strSoundCard.isNotEmpty())
339 pNewDesc->addEntry(VirtualSystemDescriptionType_SoundCard,
340 "",
341 strSoundCardOrig,
342 strSoundCard);
343
344#ifdef VBOX_WITH_USB
345 /* USB Controller */
346 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
347 if ( ( vsysThis.pelmVboxMachine
348 && pNewDesc->m->pConfig->hardwareMachine.usbController.fEnabled)
349 || vsysThis.fHasUsbController)
350 pNewDesc->addEntry(VirtualSystemDescriptionType_USBController, "", "", "");
351#endif /* VBOX_WITH_USB */
352
353 /* Network Controller */
354 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
355 if (vsysThis.pelmVboxMachine)
356 {
357 uint32_t maxNetworkAdapters = Global::getMaxNetworkAdapters(pNewDesc->m->pConfig->hardwareMachine.chipsetType);
358
359 const settings::NetworkAdaptersList &llNetworkAdapters = pNewDesc->m->pConfig->hardwareMachine.llNetworkAdapters;
360 /* Check for the constrains */
361 if (llNetworkAdapters.size() > maxNetworkAdapters)
362 addWarning(tr("The virtual system \"%s\" claims support for %zu network adapters, but VirtualBox has support for max %u network adapter only."),
363 vsysThis.strName.c_str(), llNetworkAdapters.size(), maxNetworkAdapters);
364 /* Iterate through all network adapters. */
365 settings::NetworkAdaptersList::const_iterator it1;
366 size_t a = 0;
367 for (it1 = llNetworkAdapters.begin();
368 it1 != llNetworkAdapters.end() && a < maxNetworkAdapters;
369 ++it1, ++a)
370 {
371 if (it1->fEnabled)
372 {
373 Utf8Str strMode = convertNetworkAttachmentTypeToString(it1->mode);
374 pNewDesc->addEntry(VirtualSystemDescriptionType_NetworkAdapter,
375 "", // ref
376 strMode, // orig
377 Utf8StrFmt("%RU32", (uint32_t)it1->type), // conf
378 0,
379 Utf8StrFmt("slot=%RU32;type=%s", it1->ulSlot, strMode.c_str())); // extra conf
380 }
381 }
382 }
383 /* else we use the ovf configuration. */
384 else if (size_t cEthernetAdapters = vsysThis.llEthernetAdapters.size() > 0)
385 {
386 uint32_t maxNetworkAdapters = Global::getMaxNetworkAdapters(ChipsetType_PIIX3);
387
388 /* Check for the constrains */
389 if (cEthernetAdapters > maxNetworkAdapters)
390 addWarning(tr("The virtual system \"%s\" claims support for %zu network adapters, but VirtualBox has support for max %u network adapter only."),
391 vsysThis.strName.c_str(), cEthernetAdapters, maxNetworkAdapters);
392
393 /* Get the default network adapter type for the selected guest OS */
394 NetworkAdapterType_T defaultAdapterVBox = NetworkAdapterType_Am79C970A;
395 rc = pGuestOSType->COMGETTER(AdapterType)(&defaultAdapterVBox);
396 if (FAILED(rc)) throw rc;
397
398 ovf::EthernetAdaptersList::const_iterator itEA;
399 /* Iterate through all abstract networks. Ignore network cards
400 * which exceed the limit of VirtualBox. */
401 size_t a = 0;
402 for (itEA = vsysThis.llEthernetAdapters.begin();
403 itEA != vsysThis.llEthernetAdapters.end() && a < maxNetworkAdapters;
404 ++itEA, ++a)
405 {
406 const ovf::EthernetAdapter &ea = *itEA; // logical network to connect to
407 Utf8Str strNetwork = ea.strNetworkName;
408 // make sure it's one of these two
409 if ( (strNetwork.compare("Null", Utf8Str::CaseInsensitive))
410 && (strNetwork.compare("NAT", Utf8Str::CaseInsensitive))
411 && (strNetwork.compare("Bridged", Utf8Str::CaseInsensitive))
412 && (strNetwork.compare("Internal", Utf8Str::CaseInsensitive))
413 && (strNetwork.compare("HostOnly", Utf8Str::CaseInsensitive))
414 && (strNetwork.compare("Generic", Utf8Str::CaseInsensitive))
415 )
416 strNetwork = "Bridged"; // VMware assumes this is the default apparently
417
418 /* Figure out the hardware type */
419 NetworkAdapterType_T nwAdapterVBox = defaultAdapterVBox;
420 if (!ea.strAdapterType.compare("PCNet32", Utf8Str::CaseInsensitive))
421 {
422 /* If the default adapter is already one of the two
423 * PCNet adapters use the default one. If not use the
424 * Am79C970A as fallback. */
425 if (!(defaultAdapterVBox == NetworkAdapterType_Am79C970A ||
426 defaultAdapterVBox == NetworkAdapterType_Am79C973))
427 nwAdapterVBox = NetworkAdapterType_Am79C970A;
428 }
429#ifdef VBOX_WITH_E1000
430 /* VMWare accidentally write this with VirtualCenter 3.5,
431 so make sure in this case always to use the VMWare one */
432 else if (!ea.strAdapterType.compare("E10000", Utf8Str::CaseInsensitive))
433 nwAdapterVBox = NetworkAdapterType_I82545EM;
434 else if (!ea.strAdapterType.compare("E1000", Utf8Str::CaseInsensitive))
435 {
436 /* Check if this OVF was written by VirtualBox */
437 if (Utf8Str(vsysThis.strVirtualSystemType).contains("virtualbox", Utf8Str::CaseInsensitive))
438 {
439 /* If the default adapter is already one of the three
440 * E1000 adapters use the default one. If not use the
441 * I82545EM as fallback. */
442 if (!(defaultAdapterVBox == NetworkAdapterType_I82540EM ||
443 defaultAdapterVBox == NetworkAdapterType_I82543GC ||
444 defaultAdapterVBox == NetworkAdapterType_I82545EM))
445 nwAdapterVBox = NetworkAdapterType_I82540EM;
446 }
447 else
448 /* Always use this one since it's what VMware uses */
449 nwAdapterVBox = NetworkAdapterType_I82545EM;
450 }
451#endif /* VBOX_WITH_E1000 */
452
453 pNewDesc->addEntry(VirtualSystemDescriptionType_NetworkAdapter,
454 "", // ref
455 ea.strNetworkName, // orig
456 Utf8StrFmt("%RU32", (uint32_t)nwAdapterVBox), // conf
457 0,
458 Utf8StrFmt("type=%s", strNetwork.c_str())); // extra conf
459 }
460 }
461
462 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
463 bool fFloppy = false;
464 bool fDVD = false;
465 if (vsysThis.pelmVboxMachine)
466 {
467 settings::StorageControllersList &llControllers = pNewDesc->m->pConfig->storageMachine.llStorageControllers;
468 settings::StorageControllersList::iterator it3;
469 for (it3 = llControllers.begin();
470 it3 != llControllers.end();
471 ++it3)
472 {
473 settings::AttachedDevicesList &llAttachments = it3->llAttachedDevices;
474 settings::AttachedDevicesList::iterator it4;
475 for (it4 = llAttachments.begin();
476 it4 != llAttachments.end();
477 ++it4)
478 {
479 fDVD |= it4->deviceType == DeviceType_DVD;
480 fFloppy |= it4->deviceType == DeviceType_Floppy;
481 if (fFloppy && fDVD)
482 break;
483 }
484 if (fFloppy && fDVD)
485 break;
486 }
487 }
488 else
489 {
490 fFloppy = vsysThis.fHasFloppyDrive;
491 fDVD = vsysThis.fHasCdromDrive;
492 }
493 /* Floppy Drive */
494 if (fFloppy)
495 pNewDesc->addEntry(VirtualSystemDescriptionType_Floppy, "", "", "");
496 /* CD Drive */
497 if (fDVD)
498 pNewDesc->addEntry(VirtualSystemDescriptionType_CDROM, "", "", "");
499
500 /* Hard disk Controller */
501 uint16_t cIDEused = 0;
502 uint16_t cSATAused = 0; NOREF(cSATAused);
503 uint16_t cSCSIused = 0; NOREF(cSCSIused);
504 ovf::ControllersMap::const_iterator hdcIt;
505 /* Iterate through all hard disk controllers */
506 for (hdcIt = vsysThis.mapControllers.begin();
507 hdcIt != vsysThis.mapControllers.end();
508 ++hdcIt)
509 {
510 const ovf::HardDiskController &hdc = hdcIt->second;
511 Utf8Str strControllerID = Utf8StrFmt("%RI32", (uint32_t)hdc.idController);
512
513 switch (hdc.system)
514 {
515 case ovf::HardDiskController::IDE:
516 /* Check for the constrains */
517 if (cIDEused < 4)
518 {
519 // @todo: figure out the IDE types
520 /* Use PIIX4 as default */
521 Utf8Str strType = "PIIX4";
522 if (!hdc.strControllerType.compare("PIIX3", Utf8Str::CaseInsensitive))
523 strType = "PIIX3";
524 else if (!hdc.strControllerType.compare("ICH6", Utf8Str::CaseInsensitive))
525 strType = "ICH6";
526 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
527 strControllerID, // strRef
528 hdc.strControllerType, // aOvfValue
529 strType); // aVboxValue
530 }
531 else
532 /* Warn only once */
533 if (cIDEused == 2)
534 addWarning(tr("The virtual \"%s\" system requests support for more than two IDE controller channels, but VirtualBox supports only two."),
535 vsysThis.strName.c_str());
536
537 ++cIDEused;
538 break;
539
540 case ovf::HardDiskController::SATA:
541 /* Check for the constrains */
542 if (cSATAused < 1)
543 {
544 // @todo: figure out the SATA types
545 /* We only support a plain AHCI controller, so use them always */
546 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSATA,
547 strControllerID,
548 hdc.strControllerType,
549 "AHCI");
550 }
551 else
552 {
553 /* Warn only once */
554 if (cSATAused == 1)
555 addWarning(tr("The virtual system \"%s\" requests support for more than one SATA controller, but VirtualBox has support for only one"),
556 vsysThis.strName.c_str());
557
558 }
559 ++cSATAused;
560 break;
561
562 case ovf::HardDiskController::SCSI:
563 /* Check for the constrains */
564 if (cSCSIused < 1)
565 {
566 VirtualSystemDescriptionType_T vsdet = VirtualSystemDescriptionType_HardDiskControllerSCSI;
567 Utf8Str hdcController = "LsiLogic";
568 if (!hdc.strControllerType.compare("lsilogicsas", Utf8Str::CaseInsensitive))
569 {
570 // OVF considers SAS a variant of SCSI but VirtualBox considers it a class of its own
571 vsdet = VirtualSystemDescriptionType_HardDiskControllerSAS;
572 hdcController = "LsiLogicSas";
573 }
574 else if (!hdc.strControllerType.compare("BusLogic", Utf8Str::CaseInsensitive))
575 hdcController = "BusLogic";
576 pNewDesc->addEntry(vsdet,
577 strControllerID,
578 hdc.strControllerType,
579 hdcController);
580 }
581 else
582 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."),
583 vsysThis.strName.c_str(),
584 hdc.strControllerType.c_str(),
585 strControllerID.c_str());
586 ++cSCSIused;
587 break;
588 }
589 }
590
591 /* Hard disks */
592 if (vsysThis.mapVirtualDisks.size() > 0)
593 {
594 ovf::VirtualDisksMap::const_iterator itVD;
595 /* Iterate through all hard disks ()*/
596 for (itVD = vsysThis.mapVirtualDisks.begin();
597 itVD != vsysThis.mapVirtualDisks.end();
598 ++itVD)
599 {
600 const ovf::VirtualDisk &hd = itVD->second;
601 /* Get the associated disk image */
602 const ovf::DiskImage &di = m->pReader->m_mapDisks[hd.strDiskId];
603
604 // @todo:
605 // - figure out all possible vmdk formats we also support
606 // - figure out if there is a url specifier for vhd already
607 // - we need a url specifier for the vdi format
608 if ( di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#sparse", Utf8Str::CaseInsensitive)
609 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized", Utf8Str::CaseInsensitive)
610 || di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
611 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
612 )
613 {
614 /* If the href is empty use the VM name as filename */
615 Utf8Str strFilename = di.strHref;
616 if (!strFilename.length())
617 strFilename = Utf8StrFmt("%s.vmdk", nameVBox.c_str());
618
619 Utf8Str strTargetPath = Utf8Str(strMachineFolder)
620 .append(RTPATH_DELIMITER)
621 .append(di.strHref);
622 searchUniqueDiskImageFilePath(strTargetPath);
623
624 /* find the description for the hard disk controller
625 * that has the same ID as hd.idController */
626 const VirtualSystemDescriptionEntry *pController;
627 if (!(pController = pNewDesc->findControllerFromID(hd.idController)))
628 throw setError(E_FAIL,
629 tr("Cannot find hard disk controller with OVF instance ID %RI32 to which disk \"%s\" should be attached"),
630 hd.idController,
631 di.strHref.c_str());
632
633 /* controller to attach to, and the bus within that controller */
634 Utf8StrFmt strExtraConfig("controller=%RI16;channel=%RI16",
635 pController->ulIndex,
636 hd.ulAddressOnParent);
637 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskImage,
638 hd.strDiskId,
639 di.strHref,
640 strTargetPath,
641 di.ulSuggestedSizeMB,
642 strExtraConfig);
643 }
644 else
645 throw setError(VBOX_E_FILE_ERROR,
646 tr("Unsupported format for virtual disk image in OVF: \"%s\"", di.strFormat.c_str()));
647 }
648 }
649
650 m->virtualSystemDescriptions.push_back(pNewDesc);
651 }
652 }
653 catch (HRESULT aRC)
654 {
655 /* On error we clear the list & return */
656 m->virtualSystemDescriptions.clear();
657 rc = aRC;
658 }
659
660 // reset the appliance state
661 alock.acquire();
662 m->state = Data::ApplianceIdle;
663
664 return rc;
665}
666
667/**
668 * Public method implementation. This creates one or more new machines according to the
669 * VirtualSystemScription instances created by Appliance::Interpret().
670 * Thread implementation is in Appliance::importImpl().
671 * @param aProgress
672 * @return
673 */
674STDMETHODIMP Appliance::ImportMachines(ComSafeArrayIn(ImportOptions_T, options), IProgress **aProgress)
675{
676 CheckComArgOutPointerValid(aProgress);
677
678 AutoCaller autoCaller(this);
679 if (FAILED(autoCaller.rc())) return autoCaller.rc();
680
681 if (options != NULL)
682 m->optList = com::SafeArray<ImportOptions_T>(ComSafeArrayInArg(options)).toList();
683
684 AssertReturn(!(m->optList.contains(ImportOptions_KeepAllMACs) && m->optList.contains(ImportOptions_KeepNATMACs)), E_INVALIDARG);
685
686 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
687
688 // do not allow entering this method if the appliance is busy reading or writing
689 if (!isApplianceIdle())
690 return E_ACCESSDENIED;
691
692 if (!m->pReader)
693 return setError(E_FAIL,
694 tr("Cannot import machines without reading it first (call read() before importMachines())"));
695
696 ComObjPtr<Progress> progress;
697 HRESULT rc = S_OK;
698 try
699 {
700 rc = importImpl(m->locInfo, progress);
701 }
702 catch (HRESULT aRC)
703 {
704 rc = aRC;
705 }
706
707 if (SUCCEEDED(rc))
708 /* Return progress to the caller */
709 progress.queryInterfaceTo(aProgress);
710
711 return rc;
712}
713
714////////////////////////////////////////////////////////////////////////////////
715//
716// Appliance private methods
717//
718////////////////////////////////////////////////////////////////////////////////
719
720
721/*******************************************************************************
722 * Read stuff
723 ******************************************************************************/
724
725/**
726 * Implementation for reading an OVF. This starts a new thread which will call
727 * Appliance::taskThreadImportOrExport() which will then call readFS() or readS3().
728 * This will then open the OVF with ovfreader.cpp.
729 *
730 * This is in a separate private method because it is used from three locations:
731 *
732 * 1) from the public Appliance::Read().
733 *
734 * 2) in a second worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl(), which
735 * called Appliance::readFSOVA(), which called Appliance::importImpl(), which then called this again.
736 *
737 * 3) from Appliance::readS3(), which got called from a previous instance of Appliance::taskThreadImportOrExport().
738 *
739 * @param aLocInfo
740 * @param aProgress
741 * @return
742 */
743HRESULT Appliance::readImpl(const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
744{
745 BstrFmt bstrDesc = BstrFmt(tr("Reading appliance '%s'"),
746 aLocInfo.strPath.c_str());
747 HRESULT rc;
748 /* Create the progress object */
749 aProgress.createObject();
750 if (aLocInfo.storageType == VFSType_File)
751 /* 1 operation only */
752 rc = aProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
753 bstrDesc.raw(),
754 TRUE /* aCancelable */);
755 else
756 /* 4/5 is downloading, 1/5 is reading */
757 rc = aProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
758 bstrDesc.raw(),
759 TRUE /* aCancelable */,
760 2, // ULONG cOperations,
761 5, // ULONG ulTotalOperationsWeight,
762 BstrFmt(tr("Download appliance '%s'"),
763 aLocInfo.strPath.c_str()).raw(), // CBSTR bstrFirstOperationDescription,
764 4); // ULONG ulFirstOperationWeight,
765 if (FAILED(rc)) throw rc;
766
767 /* Initialize our worker task */
768 std::auto_ptr<TaskOVF> task(new TaskOVF(this, TaskOVF::Read, aLocInfo, aProgress));
769
770 rc = task->startThread();
771 if (FAILED(rc)) throw rc;
772
773 /* Don't destruct on success */
774 task.release();
775
776 return rc;
777}
778
779/**
780 * Actual worker code for reading an OVF from disk. This is called from Appliance::taskThreadImportOrExport()
781 * and therefore runs on the OVF read worker thread. This opens the OVF with ovfreader.cpp.
782 *
783 * This runs in two contexts:
784 *
785 * 1) in a first worker thread; in that case, Appliance::Read() called Appliance::readImpl();
786 *
787 * 2) in a second worker thread; in that case, Appliance::Read() called Appliance::readImpl(), which
788 * called Appliance::readS3(), which called Appliance::readImpl(), which then called this.
789 *
790 * @param pTask
791 * @return
792 */
793HRESULT Appliance::readFS(TaskOVF *pTask)
794{
795 LogFlowFuncEnter();
796 LogFlowFunc(("Appliance %p\n", this));
797
798 AutoCaller autoCaller(this);
799 if (FAILED(autoCaller.rc())) return autoCaller.rc();
800
801 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
802
803 HRESULT rc = S_OK;
804
805 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
806 rc = readFSOVF(pTask);
807 else
808 rc = readFSOVA(pTask);
809
810 LogFlowFunc(("rc=%Rhrc\n", rc));
811 LogFlowFuncLeave();
812
813 return rc;
814}
815
816HRESULT Appliance::readFSOVF(TaskOVF *pTask)
817{
818 LogFlowFuncEnter();
819
820 HRESULT rc = S_OK;
821 int vrc = VINF_SUCCESS;
822
823 PVDINTERFACEIO pShaIo = 0;
824 PVDINTERFACEIO pFileIo = 0;
825 do
826 {
827 try
828 {
829 /* Create the necessary file access interfaces. */
830 pFileIo = FileCreateInterface();
831 if (!pFileIo)
832 {
833 rc = E_OUTOFMEMORY;
834 break;
835 }
836
837 Utf8Str strMfFile = Utf8Str(pTask->locInfo.strPath).stripExt().append(".mf");
838
839 if (RTFileExists(strMfFile.c_str()))
840 {
841 SHASTORAGE storage;
842 RT_ZERO(storage);
843
844 pShaIo = ShaCreateInterface();
845 if (!pShaIo)
846 {
847 rc = E_OUTOFMEMORY;
848 break;
849 }
850
851 //read the manifest file and find a type of used digest
852 RTFILE pFile = NULL;
853 RTFileOpen(&pFile, strMfFile.c_str(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
854 if(RT_SUCCESS(vrc) && pFile != NULL)
855 {
856 uint64_t size = 0;
857 uint64_t readed = 0;
858 void *pBuf;
859
860 vrc = RTFileGetSize(pFile, &size);
861 if(RT_SUCCESS(vrc) && size > 0)
862 pBuf = RTMemAllocZ(size);
863 else
864 throw vrc;
865
866 vrc = RTFileRead(pFile, pBuf, size, &readed);
867
868 if (RT_FAILURE(vrc))
869 {
870 if (pBuf)
871 RTMemFree(pBuf);
872 throw setError(VBOX_E_FILE_ERROR,
873 tr("Could not read manifest file '%s' (%Rrc)"),
874 RTPathFilename(strMfFile.c_str()), vrc);
875 }
876
877 RTDIGESTTYPE digestType = RTDIGESTTYPE_UNKNOWN;
878 vrc = RTManifestVerifyDigestType(pBuf, readed, digestType);
879
880 if (RT_FAILURE(vrc))
881 {
882 if (pBuf)
883 RTMemFree(pBuf);
884 throw setError(VBOX_E_FILE_ERROR,
885 tr("Could not verify supported digest types in the manifest file '%s' (%Rrc)"),
886 RTPathFilename(strMfFile.c_str()), vrc);
887 }
888
889 storage.fCreateDigest = true;
890
891 if (digestType == RTDIGESTTYPE_SHA256)
892 {
893 storage.fSha256 = true;
894 }
895 else
896 {
897 storage.fSha256 = false;
898 }
899 }
900
901 ///////////////////////////////////////////
902
903 vrc = VDInterfaceAdd(&pFileIo->Core, "Appliance::IOFile",
904 VDINTERFACETYPE_IO, 0, sizeof(VDINTERFACEIO),
905 &storage.pVDImageIfaces);
906 if (RT_FAILURE(vrc))
907 rc = setError(VBOX_E_IPRT_ERROR, "Creation of the VD interface failed (%Rrc)", vrc);
908
909 storage.fCreateDigest = true;
910
911 rc = readFSImpl(pTask, pTask->locInfo.strPath, pShaIo, &storage);
912 }
913 else
914 rc = readFSImpl(pTask, pTask->locInfo.strPath, pFileIo, NULL);
915 }
916 catch (HRESULT rc2)
917 {
918 rc = rc2;
919 }
920 catch (int rc2)
921 {
922 rc = rc2;
923 }
924
925 }while(0);
926
927 /* Cleanup */
928 if (pShaIo)
929 RTMemFree(pShaIo);
930 if (pFileIo)
931 RTMemFree(pFileIo);
932
933 LogFlowFunc(("rc=%Rhrc\n", rc));
934 LogFlowFuncLeave();
935
936 return rc;
937}
938
939HRESULT Appliance::readFSOVA(TaskOVF *pTask)
940{
941 LogFlowFuncEnter();
942
943 RTTAR tar;
944 int vrc = RTTarOpen(&tar, pTask->locInfo.strPath.c_str(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE, true);
945 if (RT_FAILURE(vrc))
946 return setError(VBOX_E_FILE_ERROR,
947 tr("Could not open OVA file '%s' (%Rrc)"),
948 pTask->locInfo.strPath.c_str(), vrc);
949
950 HRESULT rc = S_OK;
951
952 PVDINTERFACEIO pShaIo = 0;
953 PVDINTERFACEIO pTarIo = 0;
954 char *pszFilename = 0;
955 do
956 {
957 vrc = RTTarCurrentFile(tar, &pszFilename);
958 if (RT_FAILURE(vrc))
959 {
960 rc = VBOX_E_FILE_ERROR;
961 break;
962 }
963 pShaIo = ShaCreateInterface();
964 if (!pShaIo)
965 {
966 rc = E_OUTOFMEMORY;
967 break;
968 }
969 pTarIo = TarCreateInterface();
970 if (!pTarIo)
971 {
972 rc = E_OUTOFMEMORY;
973 break;
974 }
975 SHASTORAGE storage;
976 RT_ZERO(storage);
977 vrc = VDInterfaceAdd(&pTarIo->Core, "Appliance::IOTar",
978 VDINTERFACETYPE_IO, tar, sizeof(VDINTERFACEIO),
979 &storage.pVDImageIfaces);
980 if (RT_FAILURE(vrc))
981 {
982 rc = setError(VBOX_E_IPRT_ERROR, "Creation of the VD interface failed (%Rrc)", vrc);
983 break;
984 }
985 rc = readFSImpl(pTask, pszFilename, pShaIo, &storage);
986 }while(0);
987
988 RTTarClose(tar);
989
990 /* Cleanup */
991 if (pszFilename)
992 RTMemFree(pszFilename);
993 if (pShaIo)
994 RTMemFree(pShaIo);
995 if (pTarIo)
996 RTMemFree(pTarIo);
997
998 LogFlowFunc(("rc=%Rhrc\n", rc));
999 LogFlowFuncLeave();
1000
1001 return rc;
1002}
1003
1004HRESULT Appliance::readFSImpl(TaskOVF *pTask, const RTCString &strFilename, PVDINTERFACEIO pIfIo, PSHASTORAGE pStorage)
1005{
1006 LogFlowFuncEnter();
1007
1008 HRESULT rc = S_OK;
1009
1010 pStorage->fCreateDigest = true;
1011
1012 void *pvTmpBuf = 0;
1013 try
1014 {
1015 /* Read the OVF into a memory buffer */
1016 size_t cbSize = 0;
1017 int vrc = ShaReadBuf(strFilename.c_str(), &pvTmpBuf, &cbSize, pIfIo, pStorage);
1018 if ( RT_FAILURE(vrc)
1019 || !pvTmpBuf)
1020 throw setError(VBOX_E_FILE_ERROR,
1021 tr("Could not read OVF file '%s' (%Rrc)"),
1022 RTPathFilename(strFilename.c_str()), vrc);
1023 /* Copy the SHA1/SHA256 sum of the OVF file for later validation */
1024 m->strOVFSHADigest = pStorage->strDigest;
1025 /* Read & parse the XML structure of the OVF file */
1026 m->pReader = new ovf::OVFReader(pvTmpBuf, cbSize, pTask->locInfo.strPath);
1027 }
1028 catch (RTCError &x) // includes all XML exceptions
1029 {
1030 rc = setError(VBOX_E_FILE_ERROR,
1031 x.what());
1032 }
1033 catch (HRESULT aRC)
1034 {
1035 rc = aRC;
1036 }
1037
1038 /* Cleanup */
1039 if (pvTmpBuf)
1040 RTMemFree(pvTmpBuf);
1041
1042 LogFlowFunc(("rc=%Rhrc\n", rc));
1043 LogFlowFuncLeave();
1044
1045 return rc;
1046}
1047
1048#ifdef VBOX_WITH_S3
1049/**
1050 * Worker code for reading OVF from the cloud. This is called from Appliance::taskThreadImportOrExport()
1051 * in S3 mode and therefore runs on the OVF read worker thread. This then starts a second worker
1052 * thread to create temporary files (see Appliance::readFS()).
1053 *
1054 * @param pTask
1055 * @return
1056 */
1057HRESULT Appliance::readS3(TaskOVF *pTask)
1058{
1059 LogFlowFuncEnter();
1060 LogFlowFunc(("Appliance %p\n", this));
1061
1062 AutoCaller autoCaller(this);
1063 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1064
1065 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1066
1067 HRESULT rc = S_OK;
1068 int vrc = VINF_SUCCESS;
1069 RTS3 hS3 = NIL_RTS3;
1070 char szOSTmpDir[RTPATH_MAX];
1071 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
1072 /* The template for the temporary directory created below */
1073 char *pszTmpDir = RTPathJoinA(szOSTmpDir, "vbox-ovf-XXXXXX");
1074 list< pair<Utf8Str, ULONG> > filesList;
1075 Utf8Str strTmpOvf;
1076
1077 try
1078 {
1079 /* Extract the bucket */
1080 Utf8Str tmpPath = pTask->locInfo.strPath;
1081 Utf8Str bucket;
1082 parseBucket(tmpPath, bucket);
1083
1084 /* We need a temporary directory which we can put the OVF file & all
1085 * disk images in */
1086 vrc = RTDirCreateTemp(pszTmpDir, 0700);
1087 if (RT_FAILURE(vrc))
1088 throw setError(VBOX_E_FILE_ERROR,
1089 tr("Cannot create temporary directory '%s'"), pszTmpDir);
1090
1091 /* The temporary name of the target OVF file */
1092 strTmpOvf = Utf8StrFmt("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
1093
1094 /* Next we have to download the OVF */
1095 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
1096 if (RT_FAILURE(vrc))
1097 throw setError(VBOX_E_IPRT_ERROR,
1098 tr("Cannot create S3 service handler"));
1099 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
1100
1101 /* Get it */
1102 char *pszFilename = RTPathFilename(strTmpOvf.c_str());
1103 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strTmpOvf.c_str());
1104 if (RT_FAILURE(vrc))
1105 {
1106 if (vrc == VERR_S3_CANCELED)
1107 throw S_OK; /* todo: !!!!!!!!!!!!! */
1108 else if (vrc == VERR_S3_ACCESS_DENIED)
1109 throw setError(E_ACCESSDENIED,
1110 tr("Cannot download file '%s' from S3 storage server (Access denied). Make sure that your credentials are right."
1111 "Also check that your host clock is properly synced"),
1112 pszFilename);
1113 else if (vrc == VERR_S3_NOT_FOUND)
1114 throw setError(VBOX_E_FILE_ERROR,
1115 tr("Cannot download file '%s' from S3 storage server (File not found)"), pszFilename);
1116 else
1117 throw setError(VBOX_E_IPRT_ERROR,
1118 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
1119 }
1120
1121 /* Close the connection early */
1122 RTS3Destroy(hS3);
1123 hS3 = NIL_RTS3;
1124
1125 pTask->pProgress->SetNextOperation(Bstr(tr("Reading")).raw(), 1);
1126
1127 /* Prepare the temporary reading of the OVF */
1128 ComObjPtr<Progress> progress;
1129 LocationInfo li;
1130 li.strPath = strTmpOvf;
1131 /* Start the reading from the fs */
1132 rc = readImpl(li, progress);
1133 if (FAILED(rc)) throw rc;
1134
1135 /* Unlock the appliance for the reading thread */
1136 appLock.release();
1137 /* Wait until the reading is done, but report the progress back to the
1138 caller */
1139 ComPtr<IProgress> progressInt(progress);
1140 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
1141
1142 /* Again lock the appliance for the next steps */
1143 appLock.acquire();
1144 }
1145 catch(HRESULT aRC)
1146 {
1147 rc = aRC;
1148 }
1149 /* Cleanup */
1150 RTS3Destroy(hS3);
1151 /* Delete all files which where temporary created */
1152 if (RTPathExists(strTmpOvf.c_str()))
1153 {
1154 vrc = RTFileDelete(strTmpOvf.c_str());
1155 if (RT_FAILURE(vrc))
1156 rc = setError(VBOX_E_FILE_ERROR,
1157 tr("Cannot delete file '%s' (%Rrc)"), strTmpOvf.c_str(), vrc);
1158 }
1159 /* Delete the temporary directory */
1160 if (RTPathExists(pszTmpDir))
1161 {
1162 vrc = RTDirRemove(pszTmpDir);
1163 if (RT_FAILURE(vrc))
1164 rc = setError(VBOX_E_FILE_ERROR,
1165 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
1166 }
1167 if (pszTmpDir)
1168 RTStrFree(pszTmpDir);
1169
1170 LogFlowFunc(("rc=%Rhrc\n", rc));
1171 LogFlowFuncLeave();
1172
1173 return rc;
1174}
1175#endif /* VBOX_WITH_S3 */
1176
1177/*******************************************************************************
1178 * Import stuff
1179 ******************************************************************************/
1180
1181/**
1182 * Implementation for importing OVF data into VirtualBox. This starts a new thread which will call
1183 * Appliance::taskThreadImportOrExport().
1184 *
1185 * This creates one or more new machines according to the VirtualSystemScription instances created by
1186 * Appliance::Interpret().
1187 *
1188 * This is in a separate private method because it is used from two locations:
1189 *
1190 * 1) from the public Appliance::ImportMachines().
1191 * 2) from Appliance::importS3(), which got called from a previous instance of Appliance::taskThreadImportOrExport().
1192 *
1193 * @param aLocInfo
1194 * @param aProgress
1195 * @return
1196 */
1197HRESULT Appliance::importImpl(const LocationInfo &locInfo,
1198 ComObjPtr<Progress> &progress)
1199{
1200 HRESULT rc = S_OK;
1201
1202 SetUpProgressMode mode;
1203 if (locInfo.storageType == VFSType_File)
1204 mode = ImportFile;
1205 else
1206 mode = ImportS3;
1207
1208 rc = setUpProgress(progress,
1209 BstrFmt(tr("Importing appliance '%s'"), locInfo.strPath.c_str()),
1210 mode);
1211 if (FAILED(rc)) throw rc;
1212
1213 /* Initialize our worker task */
1214 std::auto_ptr<TaskOVF> task(new TaskOVF(this, TaskOVF::Import, locInfo, progress));
1215
1216 rc = task->startThread();
1217 if (FAILED(rc)) throw rc;
1218
1219 /* Don't destruct on success */
1220 task.release();
1221
1222 return rc;
1223}
1224
1225/**
1226 * Actual worker code for importing OVF data into VirtualBox. This is called from Appliance::taskThreadImportOrExport()
1227 * and therefore runs on the OVF import worker thread. This creates one or more new machines according to the
1228 * VirtualSystemScription instances created by Appliance::Interpret().
1229 *
1230 * This runs in three contexts:
1231 *
1232 * 1) in a first worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl();
1233 *
1234 * 2) in a second worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl(), which
1235 * called Appliance::importFSOVA(), which called Appliance::importImpl(), which then called this again.
1236 *
1237 * 3) in a second worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl(), which
1238 * called Appliance::importS3(), which called Appliance::importImpl(), which then called this again.
1239 *
1240 * @param pTask
1241 * @return
1242 */
1243HRESULT Appliance::importFS(TaskOVF *pTask)
1244{
1245
1246 LogFlowFuncEnter();
1247 LogFlowFunc(("Appliance %p\n", this));
1248
1249 AutoCaller autoCaller(this);
1250 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1251
1252 /* Change the appliance state so we can safely leave the lock while doing
1253 * time-consuming disk imports; also the below method calls do all kinds of
1254 * locking which conflicts with the appliance object lock. */
1255 AutoWriteLock writeLock(this COMMA_LOCKVAL_SRC_POS);
1256 /* Check if the appliance is currently busy. */
1257 if (!isApplianceIdle())
1258 return E_ACCESSDENIED;
1259 /* Set the internal state to importing. */
1260 m->state = Data::ApplianceImporting;
1261
1262 HRESULT rc = S_OK;
1263
1264 /* Clear the list of imported machines, if any */
1265 m->llGuidsMachinesCreated.clear();
1266
1267 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
1268 rc = importFSOVF(pTask, writeLock);
1269 else
1270 rc = importFSOVA(pTask, writeLock);
1271
1272 if (FAILED(rc))
1273 {
1274 /* With _whatever_ error we've had, do a complete roll-back of
1275 * machines and disks we've created */
1276 writeLock.release();
1277 for (list<Guid>::iterator itID = m->llGuidsMachinesCreated.begin();
1278 itID != m->llGuidsMachinesCreated.end();
1279 ++itID)
1280 {
1281 Guid guid = *itID;
1282 Bstr bstrGuid = guid.toUtf16();
1283 ComPtr<IMachine> failedMachine;
1284 HRESULT rc2 = mVirtualBox->FindMachine(bstrGuid.raw(), failedMachine.asOutParam());
1285 if (SUCCEEDED(rc2))
1286 {
1287 SafeIfaceArray<IMedium> aMedia;
1288 rc2 = failedMachine->Unregister(CleanupMode_DetachAllReturnHardDisksOnly, ComSafeArrayAsOutParam(aMedia));
1289 ComPtr<IProgress> pProgress2;
1290 rc2 = failedMachine->DeleteConfig(ComSafeArrayAsInParam(aMedia), pProgress2.asOutParam());
1291 pProgress2->WaitForCompletion(-1);
1292 }
1293 }
1294 writeLock.acquire();
1295 }
1296
1297 /* Reset the state so others can call methods again */
1298 m->state = Data::ApplianceIdle;
1299
1300 LogFlowFunc(("rc=%Rhrc\n", rc));
1301 LogFlowFuncLeave();
1302
1303 return rc;
1304}
1305
1306HRESULT Appliance::importFSOVF(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1307{
1308 LogFlowFuncEnter();
1309
1310 HRESULT rc = S_OK;
1311
1312 PVDINTERFACEIO pShaIo = NULL;
1313 PVDINTERFACEIO pFileIo = NULL;
1314 void *pvMfBuf = NULL;
1315 writeLock.release();
1316 try
1317 {
1318 /* Create the necessary file access interfaces. */
1319 pFileIo = FileCreateInterface();
1320 if (!pFileIo)
1321 throw setError(E_OUTOFMEMORY);
1322
1323 Utf8Str strMfFile = Utf8Str(pTask->locInfo.strPath).stripExt().append(".mf");
1324 /* Create the import stack for the rollback on errors. */
1325 ImportStack stack(pTask->locInfo, m->pReader->m_mapDisks, pTask->pProgress);
1326
1327 if (RTFileExists(strMfFile.c_str()))
1328 {
1329 SHASTORAGE storage;
1330 RT_ZERO(storage);
1331
1332 pShaIo = ShaCreateInterface();
1333 if (!pShaIo)
1334 throw setError(E_OUTOFMEMORY);
1335
1336 storage.fCreateDigest = true;
1337 int vrc = VDInterfaceAdd(&pFileIo->Core, "Appliance::IOFile",
1338 VDINTERFACETYPE_IO, 0, sizeof(VDINTERFACEIO),
1339 &storage.pVDImageIfaces);
1340 if (RT_FAILURE(vrc))
1341 throw setError(VBOX_E_IPRT_ERROR, "Creation of the VD interface failed (%Rrc)", vrc);
1342
1343 size_t cbMfSize = 0;
1344 storage.fCreateDigest = true;
1345 /* Now import the appliance. */
1346 importMachines(stack, pShaIo, &storage);
1347 /* Read & verify the manifest file. */
1348 /* Add the ovf file to the digest list. */
1349 stack.llSrcDisksDigest.push_front(STRPAIR(pTask->locInfo.strPath, m->strOVFSHADigest));
1350 rc = readManifestFile(strMfFile, &pvMfBuf, &cbMfSize, pShaIo, &storage);
1351 if (FAILED(rc)) throw rc;
1352 rc = verifyManifestFile(strMfFile, stack, pvMfBuf, cbMfSize);
1353 if (FAILED(rc)) throw rc;
1354 }
1355 else
1356 importMachines(stack, pFileIo, NULL);
1357 }
1358 catch (HRESULT rc2)
1359 {
1360 rc = rc2;
1361 }
1362 writeLock.acquire();
1363
1364 /* Cleanup */
1365 if (pvMfBuf)
1366 RTMemFree(pvMfBuf);
1367 if (pShaIo)
1368 RTMemFree(pShaIo);
1369 if (pFileIo)
1370 RTMemFree(pFileIo);
1371
1372 LogFlowFunc(("rc=%Rhrc\n", rc));
1373 LogFlowFuncLeave();
1374
1375 return rc;
1376}
1377
1378HRESULT Appliance::importFSOVA(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1379{
1380 LogFlowFuncEnter();
1381
1382 RTTAR tar;
1383 int vrc = RTTarOpen(&tar, pTask->locInfo.strPath.c_str(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE, true);
1384 if (RT_FAILURE(vrc))
1385 return setError(VBOX_E_FILE_ERROR,
1386 tr("Could not open OVA file '%s' (%Rrc)"),
1387 pTask->locInfo.strPath.c_str(), vrc);
1388
1389 HRESULT rc = S_OK;
1390
1391 PVDINTERFACEIO pShaIo = 0;
1392 PVDINTERFACEIO pTarIo = 0;
1393 char *pszFilename = 0;
1394 void *pvMfBuf = 0;
1395 writeLock.release();
1396 try
1397 {
1398 /* Create the necessary file access interfaces. */
1399 pShaIo = ShaCreateInterface();
1400 if (!pShaIo)
1401 throw setError(E_OUTOFMEMORY);
1402 pTarIo = TarCreateInterface();
1403 if (!pTarIo)
1404 throw setError(E_OUTOFMEMORY);
1405
1406 SHASTORAGE storage;
1407 RT_ZERO(storage);
1408 vrc = VDInterfaceAdd(&pTarIo->Core, "Appliance::IOTar",
1409 VDINTERFACETYPE_IO, tar, sizeof(VDINTERFACEIO),
1410 &storage.pVDImageIfaces);
1411 if (RT_FAILURE(vrc))
1412 throw setError(VBOX_E_IPRT_ERROR,
1413 tr("Creation of the VD interface failed (%Rrc)"), vrc);
1414
1415 /* Read the file name of the first file (need to be the ovf file). This
1416 * is how all internal files are named. */
1417 vrc = RTTarCurrentFile(tar, &pszFilename);
1418 if (RT_FAILURE(vrc))
1419 throw setError(VBOX_E_IPRT_ERROR,
1420 tr("Getting the current file within the archive failed (%Rrc)"), vrc);
1421 /* Skip the OVF file, cause this was read in IAppliance::Read already. */
1422 vrc = RTTarSeekNextFile(tar);
1423 if ( RT_FAILURE(vrc)
1424 && vrc != VERR_TAR_END_OF_FILE)
1425 throw setError(VBOX_E_IPRT_ERROR,
1426 tr("Seeking within the archive failed (%Rrc)"), vrc);
1427
1428 PVDINTERFACEIO pCallbacks = pShaIo;
1429 PSHASTORAGE pStorage = &storage;
1430
1431 /* We always need to create the digest, cause we didn't know if there
1432 * is a manifest file in the stream. */
1433 pStorage->fCreateDigest = true;
1434
1435 size_t cbMfSize = 0;
1436 Utf8Str strMfFile = Utf8Str(pszFilename).stripExt().append(".mf");
1437 /* Create the import stack for the rollback on errors. */
1438 ImportStack stack(pTask->locInfo, m->pReader->m_mapDisks, pTask->pProgress);
1439 /*
1440 * Try to read the manifest file. First try.
1441 *
1442 * Note: This isn't fatal if the file is not found. The standard
1443 * defines 3 cases.
1444 * 1. no manifest file
1445 * 2. manifest file after the OVF file
1446 * 3. manifest file after all disk files
1447 * If we want streaming capabilities, we can't check if it is there by
1448 * searching for it. We have to try to open it on all possible places.
1449 * If it fails here, we will try it again after all disks where read.
1450 */
1451 rc = readTarManifestFile(tar, strMfFile, &pvMfBuf, &cbMfSize, pCallbacks, pStorage);
1452 if (FAILED(rc)) throw rc;
1453 /* Now import the appliance. */
1454 importMachines(stack, pCallbacks, pStorage);
1455 /* Try to read the manifest file. Second try. */
1456 if (!pvMfBuf)
1457 {
1458 rc = readTarManifestFile(tar, strMfFile, &pvMfBuf, &cbMfSize, pCallbacks, pStorage);
1459 if (FAILED(rc)) throw rc;
1460 }
1461 /* If we were able to read a manifest file we can check it now. */
1462 if (pvMfBuf)
1463 {
1464 /* Add the ovf file to the digest list. */
1465 stack.llSrcDisksDigest.push_front(STRPAIR(Utf8Str(pszFilename).stripExt().append(".ovf"), m->strOVFSHADigest));
1466 rc = verifyManifestFile(strMfFile, stack, pvMfBuf, cbMfSize);
1467 if (FAILED(rc)) throw rc;
1468 }
1469 }
1470 catch (HRESULT rc2)
1471 {
1472 rc = rc2;
1473 }
1474 writeLock.acquire();
1475
1476 RTTarClose(tar);
1477
1478 /* Cleanup */
1479 if (pszFilename)
1480 RTMemFree(pszFilename);
1481 if (pvMfBuf)
1482 RTMemFree(pvMfBuf);
1483 if (pShaIo)
1484 RTMemFree(pShaIo);
1485 if (pTarIo)
1486 RTMemFree(pTarIo);
1487
1488 LogFlowFunc(("rc=%Rhrc\n", rc));
1489 LogFlowFuncLeave();
1490
1491 return rc;
1492}
1493
1494#ifdef VBOX_WITH_S3
1495/**
1496 * Worker code for importing OVF from the cloud. This is called from Appliance::taskThreadImportOrExport()
1497 * in S3 mode and therefore runs on the OVF import worker thread. This then starts a second worker
1498 * thread to import from temporary files (see Appliance::importFS()).
1499 * @param pTask
1500 * @return
1501 */
1502HRESULT Appliance::importS3(TaskOVF *pTask)
1503{
1504 LogFlowFuncEnter();
1505 LogFlowFunc(("Appliance %p\n", this));
1506
1507 AutoCaller autoCaller(this);
1508 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1509
1510 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1511
1512 int vrc = VINF_SUCCESS;
1513 RTS3 hS3 = NIL_RTS3;
1514 char szOSTmpDir[RTPATH_MAX];
1515 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
1516 /* The template for the temporary directory created below */
1517 char *pszTmpDir = RTPathJoinA(szOSTmpDir, "vbox-ovf-XXXXXX");
1518 list< pair<Utf8Str, ULONG> > filesList;
1519
1520 HRESULT rc = S_OK;
1521 try
1522 {
1523 /* Extract the bucket */
1524 Utf8Str tmpPath = pTask->locInfo.strPath;
1525 Utf8Str bucket;
1526 parseBucket(tmpPath, bucket);
1527
1528 /* We need a temporary directory which we can put the all disk images
1529 * in */
1530 vrc = RTDirCreateTemp(pszTmpDir, 0700);
1531 if (RT_FAILURE(vrc))
1532 throw setError(VBOX_E_FILE_ERROR,
1533 tr("Cannot create temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
1534
1535 /* Add every disks of every virtual system to an internal list */
1536 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
1537 for (it = m->virtualSystemDescriptions.begin();
1538 it != m->virtualSystemDescriptions.end();
1539 ++it)
1540 {
1541 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
1542 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1543 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
1544 for (itH = avsdeHDs.begin();
1545 itH != avsdeHDs.end();
1546 ++itH)
1547 {
1548 const Utf8Str &strTargetFile = (*itH)->strOvf;
1549 if (!strTargetFile.isEmpty())
1550 {
1551 /* The temporary name of the target disk file */
1552 Utf8StrFmt strTmpDisk("%s/%s", pszTmpDir, RTPathFilename(strTargetFile.c_str()));
1553 filesList.push_back(pair<Utf8Str, ULONG>(strTmpDisk, (*itH)->ulSizeMB));
1554 }
1555 }
1556 }
1557
1558 /* Next we have to download the disk images */
1559 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
1560 if (RT_FAILURE(vrc))
1561 throw setError(VBOX_E_IPRT_ERROR,
1562 tr("Cannot create S3 service handler"));
1563 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
1564
1565 /* Download all files */
1566 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
1567 {
1568 const pair<Utf8Str, ULONG> &s = (*it1);
1569 const Utf8Str &strSrcFile = s.first;
1570 /* Construct the source file name */
1571 char *pszFilename = RTPathFilename(strSrcFile.c_str());
1572 /* Advance to the next operation */
1573 if (!pTask->pProgress.isNull())
1574 pTask->pProgress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename).raw(), s.second);
1575
1576 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strSrcFile.c_str());
1577 if (RT_FAILURE(vrc))
1578 {
1579 if (vrc == VERR_S3_CANCELED)
1580 throw S_OK; /* todo: !!!!!!!!!!!!! */
1581 else if (vrc == VERR_S3_ACCESS_DENIED)
1582 throw setError(E_ACCESSDENIED,
1583 tr("Cannot download file '%s' from S3 storage server (Access denied). "
1584 "Make sure that your credentials are right. Also check that your host clock is properly synced"),
1585 pszFilename);
1586 else if (vrc == VERR_S3_NOT_FOUND)
1587 throw setError(VBOX_E_FILE_ERROR,
1588 tr("Cannot download file '%s' from S3 storage server (File not found)"),
1589 pszFilename);
1590 else
1591 throw setError(VBOX_E_IPRT_ERROR,
1592 tr("Cannot download file '%s' from S3 storage server (%Rrc)"),
1593 pszFilename, vrc);
1594 }
1595 }
1596
1597 /* Provide a OVF file (haven't to exist) so the import routine can
1598 * figure out where the disk images/manifest file are located. */
1599 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
1600 /* Now check if there is an manifest file. This is optional. */
1601 Utf8Str strManifestFile; //= queryManifestFileName(strTmpOvf);
1602// Utf8Str strManifestFile = queryManifestFileName(strTmpOvf);
1603 char *pszFilename = RTPathFilename(strManifestFile.c_str());
1604 if (!pTask->pProgress.isNull())
1605 pTask->pProgress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename).raw(), 1);
1606
1607 /* Try to download it. If the error is VERR_S3_NOT_FOUND, it isn't fatal. */
1608 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strManifestFile.c_str());
1609 if (RT_SUCCESS(vrc))
1610 filesList.push_back(pair<Utf8Str, ULONG>(strManifestFile, 0));
1611 else if (RT_FAILURE(vrc))
1612 {
1613 if (vrc == VERR_S3_CANCELED)
1614 throw S_OK; /* todo: !!!!!!!!!!!!! */
1615 else if (vrc == VERR_S3_NOT_FOUND)
1616 vrc = VINF_SUCCESS; /* Not found is ok */
1617 else if (vrc == VERR_S3_ACCESS_DENIED)
1618 throw setError(E_ACCESSDENIED,
1619 tr("Cannot download file '%s' from S3 storage server (Access denied)."
1620 "Make sure that your credentials are right. Also check that your host clock is properly synced"),
1621 pszFilename);
1622 else
1623 throw setError(VBOX_E_IPRT_ERROR,
1624 tr("Cannot download file '%s' from S3 storage server (%Rrc)"),
1625 pszFilename, vrc);
1626 }
1627
1628 /* Close the connection early */
1629 RTS3Destroy(hS3);
1630 hS3 = NIL_RTS3;
1631
1632 pTask->pProgress->SetNextOperation(BstrFmt(tr("Importing appliance")).raw(), m->ulWeightForXmlOperation);
1633
1634 ComObjPtr<Progress> progress;
1635 /* Import the whole temporary OVF & the disk images */
1636 LocationInfo li;
1637 li.strPath = strTmpOvf;
1638 rc = importImpl(li, progress);
1639 if (FAILED(rc)) throw rc;
1640
1641 /* Unlock the appliance for the fs import thread */
1642 appLock.release();
1643 /* Wait until the import is done, but report the progress back to the
1644 caller */
1645 ComPtr<IProgress> progressInt(progress);
1646 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
1647
1648 /* Again lock the appliance for the next steps */
1649 appLock.acquire();
1650 }
1651 catch(HRESULT aRC)
1652 {
1653 rc = aRC;
1654 }
1655 /* Cleanup */
1656 RTS3Destroy(hS3);
1657 /* Delete all files which where temporary created */
1658 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
1659 {
1660 const char *pszFilePath = (*it1).first.c_str();
1661 if (RTPathExists(pszFilePath))
1662 {
1663 vrc = RTFileDelete(pszFilePath);
1664 if (RT_FAILURE(vrc))
1665 rc = setError(VBOX_E_FILE_ERROR,
1666 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
1667 }
1668 }
1669 /* Delete the temporary directory */
1670 if (RTPathExists(pszTmpDir))
1671 {
1672 vrc = RTDirRemove(pszTmpDir);
1673 if (RT_FAILURE(vrc))
1674 rc = setError(VBOX_E_FILE_ERROR,
1675 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
1676 }
1677 if (pszTmpDir)
1678 RTStrFree(pszTmpDir);
1679
1680 LogFlowFunc(("rc=%Rhrc\n", rc));
1681 LogFlowFuncLeave();
1682
1683 return rc;
1684}
1685#endif /* VBOX_WITH_S3 */
1686
1687HRESULT Appliance::readManifestFile(const Utf8Str &strFile, void **ppvBuf, size_t *pcbSize, PVDINTERFACEIO pCallbacks, PSHASTORAGE pStorage)
1688{
1689 HRESULT rc = S_OK;
1690
1691 bool fOldDigest = pStorage->fCreateDigest;
1692 pStorage->fCreateDigest = false; /* No digest for the manifest file */
1693 int vrc = ShaReadBuf(strFile.c_str(), ppvBuf, pcbSize, pCallbacks, pStorage);
1694 if ( RT_FAILURE(vrc)
1695 && vrc != VERR_FILE_NOT_FOUND)
1696 rc = setError(VBOX_E_FILE_ERROR,
1697 tr("Could not read manifest file '%s' (%Rrc)"),
1698 RTPathFilename(strFile.c_str()), vrc);
1699 pStorage->fCreateDigest = fOldDigest; /* Restore the old digest creation behavior again. */
1700
1701 return rc;
1702}
1703
1704HRESULT Appliance::readTarManifestFile(RTTAR tar, const Utf8Str &strFile, void **ppvBuf, size_t *pcbSize, PVDINTERFACEIO pCallbacks, PSHASTORAGE pStorage)
1705{
1706 HRESULT rc = S_OK;
1707
1708 char *pszCurFile;
1709 int vrc = RTTarCurrentFile(tar, &pszCurFile);
1710 if (RT_SUCCESS(vrc))
1711 {
1712 if (!strcmp(pszCurFile, RTPathFilename(strFile.c_str())))
1713 rc = readManifestFile(strFile, ppvBuf, pcbSize, pCallbacks, pStorage);
1714 RTStrFree(pszCurFile);
1715 }
1716 else if (vrc != VERR_TAR_END_OF_FILE)
1717 rc = setError(VBOX_E_IPRT_ERROR, "Seeking within the archive failed (%Rrc)", vrc);
1718
1719 return rc;
1720}
1721
1722HRESULT Appliance::verifyManifestFile(const Utf8Str &strFile, ImportStack &stack, void *pvBuf, size_t cbSize)
1723{
1724 HRESULT rc = S_OK;
1725
1726 PRTMANIFESTTEST paTests = (PRTMANIFESTTEST)RTMemAlloc(sizeof(RTMANIFESTTEST) * stack.llSrcDisksDigest.size());
1727 if (!paTests)
1728 return E_OUTOFMEMORY;
1729
1730 size_t i = 0;
1731 list<STRPAIR>::const_iterator it1;
1732 for (it1 = stack.llSrcDisksDigest.begin();
1733 it1 != stack.llSrcDisksDigest.end();
1734 ++it1, ++i)
1735 {
1736 paTests[i].pszTestFile = (*it1).first.c_str();
1737 paTests[i].pszTestDigest = (*it1).second.c_str();
1738 }
1739 size_t iFailed;
1740 int vrc = RTManifestVerifyFilesBuf(pvBuf, cbSize, paTests, stack.llSrcDisksDigest.size(), &iFailed);
1741 if (RT_UNLIKELY(vrc == VERR_MANIFEST_DIGEST_MISMATCH))
1742 rc = setError(VBOX_E_FILE_ERROR,
1743 tr("The SHA1 digest of '%s' does not match the one in '%s' (%Rrc)"),
1744 RTPathFilename(paTests[iFailed].pszTestFile), RTPathFilename(strFile.c_str()), vrc);
1745 else if (RT_FAILURE(vrc))
1746 rc = setError(VBOX_E_FILE_ERROR,
1747 tr("Could not verify the content of '%s' against the available files (%Rrc)"),
1748 RTPathFilename(strFile.c_str()), vrc);
1749
1750 RTMemFree(paTests);
1751
1752 return rc;
1753}
1754
1755
1756/**
1757 * Helper that converts VirtualSystem attachment values into VirtualBox attachment values.
1758 * Throws HRESULT values on errors!
1759 *
1760 * @param hdc in: the HardDiskController structure to attach to.
1761 * @param ulAddressOnParent in: the AddressOnParent parameter from OVF.
1762 * @param controllerType out: the name of the hard disk controller to attach to (e.g. "IDE Controller").
1763 * @param lControllerPort out: the channel (controller port) of the controller to attach to.
1764 * @param lDevice out: the device number to attach to.
1765 */
1766void Appliance::convertDiskAttachmentValues(const ovf::HardDiskController &hdc,
1767 uint32_t ulAddressOnParent,
1768 Bstr &controllerType,
1769 int32_t &lControllerPort,
1770 int32_t &lDevice)
1771{
1772 Log(("Appliance::convertDiskAttachmentValues: hdc.system=%d, hdc.fPrimary=%d, ulAddressOnParent=%d\n", hdc.system, hdc.fPrimary, ulAddressOnParent));
1773
1774 switch (hdc.system)
1775 {
1776 case ovf::HardDiskController::IDE:
1777 // For the IDE bus, the port parameter can be either 0 or 1, to specify the primary
1778 // or secondary IDE controller, respectively. For the primary controller of the IDE bus,
1779 // the device number can be either 0 or 1, to specify the master or the slave device,
1780 // respectively. For the secondary IDE controller, the device number is always 1 because
1781 // the master device is reserved for the CD-ROM drive.
1782 controllerType = Bstr("IDE Controller");
1783 switch (ulAddressOnParent)
1784 {
1785 case 0: // master
1786 if (!hdc.fPrimary)
1787 {
1788 // secondary master
1789 lControllerPort = (long)1;
1790 lDevice = (long)0;
1791 }
1792 else // primary master
1793 {
1794 lControllerPort = (long)0;
1795 lDevice = (long)0;
1796 }
1797 break;
1798
1799 case 1: // slave
1800 if (!hdc.fPrimary)
1801 {
1802 // secondary slave
1803 lControllerPort = (long)1;
1804 lDevice = (long)1;
1805 }
1806 else // primary slave
1807 {
1808 lControllerPort = (long)0;
1809 lDevice = (long)1;
1810 }
1811 break;
1812
1813 // used by older VBox exports
1814 case 2: // interpret this as secondary master
1815 lControllerPort = (long)1;
1816 lDevice = (long)0;
1817 break;
1818
1819 // used by older VBox exports
1820 case 3: // interpret this as secondary slave
1821 lControllerPort = (long)1;
1822 lDevice = (long)1;
1823 break;
1824
1825 default:
1826 throw setError(VBOX_E_NOT_SUPPORTED,
1827 tr("Invalid channel %RI16 specified; IDE controllers support only 0, 1 or 2"),
1828 ulAddressOnParent);
1829 break;
1830 }
1831 break;
1832
1833 case ovf::HardDiskController::SATA:
1834 controllerType = Bstr("SATA Controller");
1835 lControllerPort = (long)ulAddressOnParent;
1836 lDevice = (long)0;
1837 break;
1838
1839 case ovf::HardDiskController::SCSI:
1840 controllerType = Bstr("SCSI Controller");
1841 lControllerPort = (long)ulAddressOnParent;
1842 lDevice = (long)0;
1843 break;
1844
1845 default: break;
1846 }
1847
1848 Log(("=> lControllerPort=%d, lDevice=%d\n", lControllerPort, lDevice));
1849}
1850
1851/**
1852 * Imports one disk image. This is common code shared between
1853 * -- importMachineGeneric() for the OVF case; in that case the information comes from
1854 * the OVF virtual systems;
1855 * -- importVBoxMachine(); in that case, the information comes from the <vbox:Machine>
1856 * tag.
1857 *
1858 * Both ways of describing machines use the OVF disk references section, so in both cases
1859 * the caller needs to pass in the ovf::DiskImage structure from ovfreader.cpp.
1860 *
1861 * As a result, in both cases, if di.strHref is empty, we create a new disk as per the OVF
1862 * spec, even though this cannot really happen in the vbox:Machine case since such data
1863 * would never have been exported.
1864 *
1865 * This advances stack.pProgress by one operation with the disk's weight.
1866 *
1867 * @param di ovfreader.cpp structure describing the disk image from the OVF that is to be imported
1868 * @param ulSizeMB Size of the disk image (for progress reporting)
1869 * @param strTargetPath Where to create the target image.
1870 * @param pTargetHD out: The newly created target disk. This also gets pushed on stack.llHardDisksCreated for cleanup.
1871 * @param stack
1872 */
1873void Appliance::importOneDiskImage(const ovf::DiskImage &di,
1874 const Utf8Str &strTargetPath,
1875 ComObjPtr<Medium> &pTargetHD,
1876 ImportStack &stack,
1877 PVDINTERFACEIO pCallbacks,
1878 PSHASTORAGE pStorage)
1879{
1880 ComObjPtr<Progress> pProgress;
1881 pProgress.createObject();
1882 HRESULT rc = pProgress->init(mVirtualBox, static_cast<IAppliance*>(this), BstrFmt(tr("Creating medium '%s'"), strTargetPath.c_str()).raw(), TRUE);
1883 if (FAILED(rc)) throw rc;
1884
1885 /* Get the system properties. */
1886 SystemProperties *pSysProps = mVirtualBox->getSystemProperties();
1887
1888 /* First of all check if the path is an UUID. If so, the user like to
1889 * import the disk into an existing path. This is useful for iSCSI for
1890 * example. */
1891 RTUUID uuid;
1892 int vrc = RTUuidFromStr(&uuid, strTargetPath.c_str());
1893 if (vrc == VINF_SUCCESS)
1894 {
1895 rc = mVirtualBox->findHardDiskById(Guid(uuid), true, &pTargetHD);
1896 if (FAILED(rc)) throw rc;
1897 }
1898 else
1899 {
1900 Utf8Str strTrgFormat = "VMDK";
1901 if (RTPathHaveExt(strTargetPath.c_str()))
1902 {
1903 char *pszExt = RTPathExt(strTargetPath.c_str());
1904 /* Figure out which format the user like to have. Default is VMDK. */
1905 ComObjPtr<MediumFormat> trgFormat = pSysProps->mediumFormatFromExtension(&pszExt[1]);
1906 if (trgFormat.isNull())
1907 throw setError(VBOX_E_NOT_SUPPORTED,
1908 tr("Could not find a valid medium format for the target disk '%s'"),
1909 strTargetPath.c_str());
1910 /* Check the capabilities. We need create capabilities. */
1911 ULONG lCabs = 0;
1912 com::SafeArray <MediumFormatCapabilities_T> mediumFormatCap;
1913 rc = trgFormat->COMGETTER(Capabilities)(ComSafeArrayAsOutParam(mediumFormatCap));
1914
1915 if (FAILED(rc)) throw rc;
1916 else
1917 {
1918 for (ULONG j = 0; j < mediumFormatCap.size(); j++)
1919 lCabs |= mediumFormatCap[j];
1920 }
1921
1922 if (!( ((lCabs & MediumFormatCapabilities_CreateFixed) == MediumFormatCapabilities_CreateFixed)
1923 || ((lCabs & MediumFormatCapabilities_CreateDynamic) == MediumFormatCapabilities_CreateDynamic)))
1924 throw setError(VBOX_E_NOT_SUPPORTED,
1925 tr("Could not find a valid medium format for the target disk '%s'"),
1926 strTargetPath.c_str());
1927 Bstr bstrFormatName;
1928 rc = trgFormat->COMGETTER(Name)(bstrFormatName.asOutParam());
1929 if (FAILED(rc)) throw rc;
1930 strTrgFormat = Utf8Str(bstrFormatName);
1931 }
1932
1933 /* Create an IMedium object. */
1934 pTargetHD.createObject();
1935 rc = pTargetHD->init(mVirtualBox,
1936 strTrgFormat,
1937 strTargetPath,
1938 Guid::Empty /* media registry: none yet */);
1939 if (FAILED(rc)) throw rc;
1940
1941 /* Now create an empty hard disk. */
1942 rc = mVirtualBox->CreateHardDisk(NULL,
1943 Bstr(strTargetPath).raw(),
1944 ComPtr<IMedium>(pTargetHD).asOutParam());
1945 if (FAILED(rc)) throw rc;
1946 }
1947
1948 const Utf8Str &strSourceOVF = di.strHref;
1949 /* Construct source file path */
1950 Utf8StrFmt strSrcFilePath("%s%c%s", stack.strSourceDir.c_str(), RTPATH_DELIMITER, strSourceOVF.c_str());
1951
1952 /* If strHref is empty we have to create a new file. */
1953 if (strSourceOVF.isEmpty())
1954 {
1955 com::SafeArray<MediumVariant_T> mediumVariant;
1956 mediumVariant.push_back(MediumVariant_Standard);
1957 /* Create a dynamic growing disk image with the given capacity. */
1958 rc = pTargetHD->CreateBaseStorage(di.iCapacity / _1M, ComSafeArrayAsInParam(mediumVariant), ComPtr<IProgress>(pProgress).asOutParam());
1959 if (FAILED(rc)) throw rc;
1960
1961 /* Advance to the next operation. */
1962 stack.pProgress->SetNextOperation(BstrFmt(tr("Creating disk image '%s'"), strTargetPath.c_str()).raw(),
1963 di.ulSuggestedSizeMB); // operation's weight, as set up with the IProgress originally
1964 }
1965 else
1966 {
1967 /* We need a proper source format description */
1968 ComObjPtr<MediumFormat> srcFormat;
1969 /* Which format to use? */
1970 Utf8Str strSrcFormat = "VDI";
1971 if ( di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#sparse", Utf8Str::CaseInsensitive)
1972 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized", Utf8Str::CaseInsensitive)
1973 || di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
1974 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
1975 )
1976 strSrcFormat = "VMDK";
1977 srcFormat = pSysProps->mediumFormat(strSrcFormat);
1978 if (srcFormat.isNull())
1979 throw setError(VBOX_E_NOT_SUPPORTED,
1980 tr("Could not find a valid medium format for the source disk '%s'"),
1981 RTPathFilename(strSrcFilePath.c_str()));
1982
1983 /* Clone the source disk image */
1984 ComObjPtr<Medium> nullParent;
1985 rc = pTargetHD->importFile(strSrcFilePath.c_str(),
1986 srcFormat,
1987 MediumVariant_Standard,
1988 pCallbacks, pStorage,
1989 nullParent,
1990 pProgress);
1991 if (FAILED(rc)) throw rc;
1992
1993 /* Advance to the next operation. */
1994 stack.pProgress->SetNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"), RTPathFilename(strSrcFilePath.c_str())).raw(),
1995 di.ulSuggestedSizeMB); // operation's weight, as set up with the IProgress originally);
1996 }
1997
1998 /* Now wait for the background disk operation to complete; this throws
1999 * HRESULTs on error. */
2000 ComPtr<IProgress> pp(pProgress);
2001 waitForAsyncProgress(stack.pProgress, pp);
2002
2003 /* Add the newly create disk path + a corresponding digest the our list for
2004 * later manifest verification. */
2005 stack.llSrcDisksDigest.push_back(STRPAIR(strSrcFilePath, pStorage ? pStorage->strDigest : ""));
2006}
2007
2008/**
2009 * Imports one OVF virtual system (described by the given ovf::VirtualSystem and VirtualSystemDescription)
2010 * into VirtualBox by creating an IMachine instance, which is returned.
2011 *
2012 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
2013 * up any leftovers from this function. For this, the given ImportStack instance has received information
2014 * about what needs cleaning up (to support rollback).
2015 *
2016 * @param vsysThis OVF virtual system (machine) to import.
2017 * @param vsdescThis Matching virtual system description (machine) to import.
2018 * @param pNewMachine out: Newly created machine.
2019 * @param stack Cleanup stack for when this throws.
2020 */
2021void Appliance::importMachineGeneric(const ovf::VirtualSystem &vsysThis,
2022 ComObjPtr<VirtualSystemDescription> &vsdescThis,
2023 ComPtr<IMachine> &pNewMachine,
2024 ImportStack &stack,
2025 PVDINTERFACEIO pCallbacks,
2026 PSHASTORAGE pStorage)
2027{
2028 HRESULT rc;
2029
2030 // Get the instance of IGuestOSType which matches our string guest OS type so we
2031 // can use recommended defaults for the new machine where OVF doesn't provide any
2032 ComPtr<IGuestOSType> osType;
2033 rc = mVirtualBox->GetGuestOSType(Bstr(stack.strOsTypeVBox).raw(), osType.asOutParam());
2034 if (FAILED(rc)) throw rc;
2035
2036 /* Create the machine */
2037 SafeArray<BSTR> groups; /* no groups */
2038 rc = mVirtualBox->CreateMachine(NULL, /* machine name: use default */
2039 Bstr(stack.strNameVBox).raw(),
2040 ComSafeArrayAsInParam(groups),
2041 Bstr(stack.strOsTypeVBox).raw(),
2042 NULL, /* aCreateFlags */
2043 pNewMachine.asOutParam());
2044 if (FAILED(rc)) throw rc;
2045
2046 // set the description
2047 if (!stack.strDescription.isEmpty())
2048 {
2049 rc = pNewMachine->COMSETTER(Description)(Bstr(stack.strDescription).raw());
2050 if (FAILED(rc)) throw rc;
2051 }
2052
2053 // CPU count
2054 rc = pNewMachine->COMSETTER(CPUCount)(stack.cCPUs);
2055 if (FAILED(rc)) throw rc;
2056
2057 if (stack.fForceHWVirt)
2058 {
2059 rc = pNewMachine->SetHWVirtExProperty(HWVirtExPropertyType_Enabled, TRUE);
2060 if (FAILED(rc)) throw rc;
2061 }
2062
2063 // RAM
2064 rc = pNewMachine->COMSETTER(MemorySize)(stack.ulMemorySizeMB);
2065 if (FAILED(rc)) throw rc;
2066
2067 /* VRAM */
2068 /* Get the recommended VRAM for this guest OS type */
2069 ULONG vramVBox;
2070 rc = osType->COMGETTER(RecommendedVRAM)(&vramVBox);
2071 if (FAILED(rc)) throw rc;
2072
2073 /* Set the VRAM */
2074 rc = pNewMachine->COMSETTER(VRAMSize)(vramVBox);
2075 if (FAILED(rc)) throw rc;
2076
2077 // I/O APIC: Generic OVF has no setting for this. Enable it if we
2078 // import a Windows VM because if if Windows was installed without IOAPIC,
2079 // it will not mind finding an one later on, but if Windows was installed
2080 // _with_ an IOAPIC, it will bluescreen if it's not found
2081 if (!stack.fForceIOAPIC)
2082 {
2083 Bstr bstrFamilyId;
2084 rc = osType->COMGETTER(FamilyId)(bstrFamilyId.asOutParam());
2085 if (FAILED(rc)) throw rc;
2086 if (bstrFamilyId == "Windows")
2087 stack.fForceIOAPIC = true;
2088 }
2089
2090 if (stack.fForceIOAPIC)
2091 {
2092 ComPtr<IBIOSSettings> pBIOSSettings;
2093 rc = pNewMachine->COMGETTER(BIOSSettings)(pBIOSSettings.asOutParam());
2094 if (FAILED(rc)) throw rc;
2095
2096 rc = pBIOSSettings->COMSETTER(IOAPICEnabled)(TRUE);
2097 if (FAILED(rc)) throw rc;
2098 }
2099
2100 if (!stack.strAudioAdapter.isEmpty())
2101 if (stack.strAudioAdapter.compare("null", Utf8Str::CaseInsensitive) != 0)
2102 {
2103 uint32_t audio = RTStrToUInt32(stack.strAudioAdapter.c_str()); // should be 0 for AC97
2104 ComPtr<IAudioAdapter> audioAdapter;
2105 rc = pNewMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam());
2106 if (FAILED(rc)) throw rc;
2107 rc = audioAdapter->COMSETTER(Enabled)(true);
2108 if (FAILED(rc)) throw rc;
2109 rc = audioAdapter->COMSETTER(AudioController)(static_cast<AudioControllerType_T>(audio));
2110 if (FAILED(rc)) throw rc;
2111 }
2112
2113#ifdef VBOX_WITH_USB
2114 /* USB Controller */
2115 ComPtr<IUSBController> usbController;
2116 rc = pNewMachine->COMGETTER(USBController)(usbController.asOutParam());
2117 if (FAILED(rc)) throw rc;
2118 rc = usbController->COMSETTER(Enabled)(stack.fUSBEnabled);
2119 if (FAILED(rc)) throw rc;
2120#endif /* VBOX_WITH_USB */
2121
2122 /* Change the network adapters */
2123 uint32_t maxNetworkAdapters = Global::getMaxNetworkAdapters(ChipsetType_PIIX3);
2124
2125 std::list<VirtualSystemDescriptionEntry*> vsdeNW = vsdescThis->findByType(VirtualSystemDescriptionType_NetworkAdapter);
2126 if (vsdeNW.size() == 0)
2127 {
2128 /* No network adapters, so we have to disable our default one */
2129 ComPtr<INetworkAdapter> nwVBox;
2130 rc = pNewMachine->GetNetworkAdapter(0, nwVBox.asOutParam());
2131 if (FAILED(rc)) throw rc;
2132 rc = nwVBox->COMSETTER(Enabled)(false);
2133 if (FAILED(rc)) throw rc;
2134 }
2135 else if (vsdeNW.size() > maxNetworkAdapters)
2136 throw setError(VBOX_E_FILE_ERROR,
2137 tr("Too many network adapters: OVF requests %d network adapters, but VirtualBox only supports %d"),
2138 vsdeNW.size(), maxNetworkAdapters);
2139 else
2140 {
2141 list<VirtualSystemDescriptionEntry*>::const_iterator nwIt;
2142 size_t a = 0;
2143 for (nwIt = vsdeNW.begin();
2144 nwIt != vsdeNW.end();
2145 ++nwIt, ++a)
2146 {
2147 const VirtualSystemDescriptionEntry* pvsys = *nwIt;
2148
2149 const Utf8Str &nwTypeVBox = pvsys->strVboxCurrent;
2150 uint32_t tt1 = RTStrToUInt32(nwTypeVBox.c_str());
2151 ComPtr<INetworkAdapter> pNetworkAdapter;
2152 rc = pNewMachine->GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
2153 if (FAILED(rc)) throw rc;
2154 /* Enable the network card & set the adapter type */
2155 rc = pNetworkAdapter->COMSETTER(Enabled)(true);
2156 if (FAILED(rc)) throw rc;
2157 rc = pNetworkAdapter->COMSETTER(AdapterType)(static_cast<NetworkAdapterType_T>(tt1));
2158 if (FAILED(rc)) throw rc;
2159
2160 // default is NAT; change to "bridged" if extra conf says so
2161 if (pvsys->strExtraConfigCurrent.endsWith("type=Bridged", Utf8Str::CaseInsensitive))
2162 {
2163 /* Attach to the right interface */
2164 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_Bridged);
2165 if (FAILED(rc)) throw rc;
2166 ComPtr<IHost> host;
2167 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
2168 if (FAILED(rc)) throw rc;
2169 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
2170 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
2171 if (FAILED(rc)) throw rc;
2172 // We search for the first host network interface which
2173 // is usable for bridged networking
2174 for (size_t j = 0;
2175 j < nwInterfaces.size();
2176 ++j)
2177 {
2178 HostNetworkInterfaceType_T itype;
2179 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
2180 if (FAILED(rc)) throw rc;
2181 if (itype == HostNetworkInterfaceType_Bridged)
2182 {
2183 Bstr name;
2184 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
2185 if (FAILED(rc)) throw rc;
2186 /* Set the interface name to attach to */
2187 pNetworkAdapter->COMSETTER(BridgedInterface)(name.raw());
2188 if (FAILED(rc)) throw rc;
2189 break;
2190 }
2191 }
2192 }
2193 /* Next test for host only interfaces */
2194 else if (pvsys->strExtraConfigCurrent.endsWith("type=HostOnly", Utf8Str::CaseInsensitive))
2195 {
2196 /* Attach to the right interface */
2197 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_HostOnly);
2198 if (FAILED(rc)) throw rc;
2199 ComPtr<IHost> host;
2200 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
2201 if (FAILED(rc)) throw rc;
2202 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
2203 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
2204 if (FAILED(rc)) throw rc;
2205 // We search for the first host network interface which
2206 // is usable for host only networking
2207 for (size_t j = 0;
2208 j < nwInterfaces.size();
2209 ++j)
2210 {
2211 HostNetworkInterfaceType_T itype;
2212 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
2213 if (FAILED(rc)) throw rc;
2214 if (itype == HostNetworkInterfaceType_HostOnly)
2215 {
2216 Bstr name;
2217 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
2218 if (FAILED(rc)) throw rc;
2219 /* Set the interface name to attach to */
2220 pNetworkAdapter->COMSETTER(HostOnlyInterface)(name.raw());
2221 if (FAILED(rc)) throw rc;
2222 break;
2223 }
2224 }
2225 }
2226 /* Next test for internal interfaces */
2227 else if (pvsys->strExtraConfigCurrent.endsWith("type=Internal", Utf8Str::CaseInsensitive))
2228 {
2229 /* Attach to the right interface */
2230 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_Internal);
2231 if (FAILED(rc)) throw rc;
2232 }
2233 /* Next test for Generic interfaces */
2234 else if (pvsys->strExtraConfigCurrent.endsWith("type=Generic", Utf8Str::CaseInsensitive))
2235 {
2236 /* Attach to the right interface */
2237 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_Generic);
2238 if (FAILED(rc)) throw rc;
2239 }
2240 }
2241 }
2242
2243 // IDE Hard disk controller
2244 std::list<VirtualSystemDescriptionEntry*> vsdeHDCIDE = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerIDE);
2245 // In OVF (at least VMware's version of it), an IDE controller has two ports, so VirtualBox's single IDE controller
2246 // with two channels and two ports each counts as two OVF IDE controllers -- so we accept one or two such IDE controllers
2247 size_t cIDEControllers = vsdeHDCIDE.size();
2248 if (cIDEControllers > 2)
2249 throw setError(VBOX_E_FILE_ERROR,
2250 tr("Too many IDE controllers in OVF; import facility only supports two"));
2251 if (vsdeHDCIDE.size() > 0)
2252 {
2253 // one or two IDE controllers present in OVF: add one VirtualBox controller
2254 ComPtr<IStorageController> pController;
2255 rc = pNewMachine->AddStorageController(Bstr("IDE Controller").raw(), StorageBus_IDE, pController.asOutParam());
2256 if (FAILED(rc)) throw rc;
2257
2258 const char *pcszIDEType = vsdeHDCIDE.front()->strVboxCurrent.c_str();
2259 if (!strcmp(pcszIDEType, "PIIX3"))
2260 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX3);
2261 else if (!strcmp(pcszIDEType, "PIIX4"))
2262 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX4);
2263 else if (!strcmp(pcszIDEType, "ICH6"))
2264 rc = pController->COMSETTER(ControllerType)(StorageControllerType_ICH6);
2265 else
2266 throw setError(VBOX_E_FILE_ERROR,
2267 tr("Invalid IDE controller type \"%s\""),
2268 pcszIDEType);
2269 if (FAILED(rc)) throw rc;
2270 }
2271
2272 /* Hard disk controller SATA */
2273 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSATA = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSATA);
2274 if (vsdeHDCSATA.size() > 1)
2275 throw setError(VBOX_E_FILE_ERROR,
2276 tr("Too many SATA controllers in OVF; import facility only supports one"));
2277 if (vsdeHDCSATA.size() > 0)
2278 {
2279 ComPtr<IStorageController> pController;
2280 const Utf8Str &hdcVBox = vsdeHDCSATA.front()->strVboxCurrent;
2281 if (hdcVBox == "AHCI")
2282 {
2283 rc = pNewMachine->AddStorageController(Bstr("SATA Controller").raw(), StorageBus_SATA, pController.asOutParam());
2284 if (FAILED(rc)) throw rc;
2285 }
2286 else
2287 throw setError(VBOX_E_FILE_ERROR,
2288 tr("Invalid SATA controller type \"%s\""),
2289 hdcVBox.c_str());
2290 }
2291
2292 /* Hard disk controller SCSI */
2293 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSCSI = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSCSI);
2294 if (vsdeHDCSCSI.size() > 1)
2295 throw setError(VBOX_E_FILE_ERROR,
2296 tr("Too many SCSI controllers in OVF; import facility only supports one"));
2297 if (vsdeHDCSCSI.size() > 0)
2298 {
2299 ComPtr<IStorageController> pController;
2300 Bstr bstrName(L"SCSI Controller");
2301 StorageBus_T busType = StorageBus_SCSI;
2302 StorageControllerType_T controllerType;
2303 const Utf8Str &hdcVBox = vsdeHDCSCSI.front()->strVboxCurrent;
2304 if (hdcVBox == "LsiLogic")
2305 controllerType = StorageControllerType_LsiLogic;
2306 else if (hdcVBox == "LsiLogicSas")
2307 {
2308 // OVF treats LsiLogicSas as a SCSI controller but VBox considers it a class of its own
2309 bstrName = L"SAS Controller";
2310 busType = StorageBus_SAS;
2311 controllerType = StorageControllerType_LsiLogicSas;
2312 }
2313 else if (hdcVBox == "BusLogic")
2314 controllerType = StorageControllerType_BusLogic;
2315 else
2316 throw setError(VBOX_E_FILE_ERROR,
2317 tr("Invalid SCSI controller type \"%s\""),
2318 hdcVBox.c_str());
2319
2320 rc = pNewMachine->AddStorageController(bstrName.raw(), busType, pController.asOutParam());
2321 if (FAILED(rc)) throw rc;
2322 rc = pController->COMSETTER(ControllerType)(controllerType);
2323 if (FAILED(rc)) throw rc;
2324 }
2325
2326 /* Hard disk controller SAS */
2327 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSAS = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSAS);
2328 if (vsdeHDCSAS.size() > 1)
2329 throw setError(VBOX_E_FILE_ERROR,
2330 tr("Too many SAS controllers in OVF; import facility only supports one"));
2331 if (vsdeHDCSAS.size() > 0)
2332 {
2333 ComPtr<IStorageController> pController;
2334 rc = pNewMachine->AddStorageController(Bstr(L"SAS Controller").raw(), StorageBus_SAS, pController.asOutParam());
2335 if (FAILED(rc)) throw rc;
2336 rc = pController->COMSETTER(ControllerType)(StorageControllerType_LsiLogicSas);
2337 if (FAILED(rc)) throw rc;
2338 }
2339
2340 /* Now its time to register the machine before we add any hard disks */
2341 rc = mVirtualBox->RegisterMachine(pNewMachine);
2342 if (FAILED(rc)) throw rc;
2343
2344 // store new machine for roll-back in case of errors
2345 Bstr bstrNewMachineId;
2346 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
2347 if (FAILED(rc)) throw rc;
2348 Guid uuidNewMachine(bstrNewMachineId);
2349 m->llGuidsMachinesCreated.push_back(uuidNewMachine);
2350
2351 // Add floppies and CD-ROMs to the appropriate controllers.
2352 std::list<VirtualSystemDescriptionEntry*> vsdeFloppy = vsdescThis->findByType(VirtualSystemDescriptionType_Floppy);
2353 if (vsdeFloppy.size() > 1)
2354 throw setError(VBOX_E_FILE_ERROR,
2355 tr("Too many floppy controllers in OVF; import facility only supports one"));
2356 std::list<VirtualSystemDescriptionEntry*> vsdeCDROM = vsdescThis->findByType(VirtualSystemDescriptionType_CDROM);
2357 if ( (vsdeFloppy.size() > 0)
2358 || (vsdeCDROM.size() > 0)
2359 )
2360 {
2361 // If there's an error here we need to close the session, so
2362 // we need another try/catch block.
2363
2364 try
2365 {
2366 // to attach things we need to open a session for the new machine
2367 rc = pNewMachine->LockMachine(stack.pSession, LockType_Write);
2368 if (FAILED(rc)) throw rc;
2369 stack.fSessionOpen = true;
2370
2371 ComPtr<IMachine> sMachine;
2372 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
2373 if (FAILED(rc)) throw rc;
2374
2375 // floppy first
2376 if (vsdeFloppy.size() == 1)
2377 {
2378 ComPtr<IStorageController> pController;
2379 rc = sMachine->AddStorageController(Bstr("Floppy Controller").raw(), StorageBus_Floppy, pController.asOutParam());
2380 if (FAILED(rc)) throw rc;
2381
2382 Bstr bstrName;
2383 rc = pController->COMGETTER(Name)(bstrName.asOutParam());
2384 if (FAILED(rc)) throw rc;
2385
2386 // this is for rollback later
2387 MyHardDiskAttachment mhda;
2388 mhda.pMachine = pNewMachine;
2389 mhda.controllerType = bstrName;
2390 mhda.lControllerPort = 0;
2391 mhda.lDevice = 0;
2392
2393 Log(("Attaching floppy\n"));
2394
2395 rc = sMachine->AttachDevice(mhda.controllerType.raw(),
2396 mhda.lControllerPort,
2397 mhda.lDevice,
2398 DeviceType_Floppy,
2399 NULL);
2400 if (FAILED(rc)) throw rc;
2401
2402 stack.llHardDiskAttachments.push_back(mhda);
2403 }
2404
2405 // CD-ROMs next
2406 for (std::list<VirtualSystemDescriptionEntry*>::const_iterator jt = vsdeCDROM.begin();
2407 jt != vsdeCDROM.end();
2408 ++jt)
2409 {
2410 // for now always attach to secondary master on IDE controller;
2411 // there seems to be no useful information in OVF where else to
2412 // attach it (@todo test with latest versions of OVF software)
2413
2414 // find the IDE controller
2415 const ovf::HardDiskController *pController = NULL;
2416 for (ovf::ControllersMap::const_iterator kt = vsysThis.mapControllers.begin();
2417 kt != vsysThis.mapControllers.end();
2418 ++kt)
2419 {
2420 if (kt->second.system == ovf::HardDiskController::IDE)
2421 {
2422 pController = &kt->second;
2423 break;
2424 }
2425 }
2426
2427 if (!pController)
2428 throw setError(VBOX_E_FILE_ERROR,
2429 tr("OVF wants a CD-ROM drive but cannot find IDE controller, which is required in this version of VirtualBox"));
2430
2431 // this is for rollback later
2432 MyHardDiskAttachment mhda;
2433 mhda.pMachine = pNewMachine;
2434
2435 convertDiskAttachmentValues(*pController,
2436 2, // interpreted as secondary master
2437 mhda.controllerType, // Bstr
2438 mhda.lControllerPort,
2439 mhda.lDevice);
2440
2441 Log(("Attaching CD-ROM to port %d on device %d\n", mhda.lControllerPort, mhda.lDevice));
2442
2443 rc = sMachine->AttachDevice(mhda.controllerType.raw(),
2444 mhda.lControllerPort,
2445 mhda.lDevice,
2446 DeviceType_DVD,
2447 NULL);
2448 if (FAILED(rc)) throw rc;
2449
2450 stack.llHardDiskAttachments.push_back(mhda);
2451 } // end for (itHD = avsdeHDs.begin();
2452
2453 rc = sMachine->SaveSettings();
2454 if (FAILED(rc)) throw rc;
2455
2456 // only now that we're done with all disks, close the session
2457 rc = stack.pSession->UnlockMachine();
2458 if (FAILED(rc)) throw rc;
2459 stack.fSessionOpen = false;
2460 }
2461 catch(HRESULT /* aRC */)
2462 {
2463 if (stack.fSessionOpen)
2464 stack.pSession->UnlockMachine();
2465
2466 throw;
2467 }
2468 }
2469
2470 // create the hard disks & connect them to the appropriate controllers
2471 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
2472 if (avsdeHDs.size() > 0)
2473 {
2474 // If there's an error here we need to close the session, so
2475 // we need another try/catch block.
2476 try
2477 {
2478 // to attach things we need to open a session for the new machine
2479 rc = pNewMachine->LockMachine(stack.pSession, LockType_Write);
2480 if (FAILED(rc)) throw rc;
2481 stack.fSessionOpen = true;
2482
2483 /* Iterate over all given disk images */
2484 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
2485 for (itHD = avsdeHDs.begin();
2486 itHD != avsdeHDs.end();
2487 ++itHD)
2488 {
2489 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
2490
2491 // vsdeHD->strRef contains the disk identifier (e.g. "vmdisk1"), which should exist
2492 // in the virtual system's disks map under that ID and also in the global images map
2493 ovf::VirtualDisksMap::const_iterator itVirtualDisk = vsysThis.mapVirtualDisks.find(vsdeHD->strRef);
2494 // and find the disk from the OVF's disk list
2495 ovf::DiskImagesMap::const_iterator itDiskImage = stack.mapDisks.find(vsdeHD->strRef);
2496 if ( (itVirtualDisk == vsysThis.mapVirtualDisks.end())
2497 || (itDiskImage == stack.mapDisks.end())
2498 )
2499 throw setError(E_FAIL,
2500 tr("Internal inconsistency looking up disk image '%s'"),
2501 vsdeHD->strRef.c_str());
2502
2503 const ovf::DiskImage &ovfDiskImage = itDiskImage->second;
2504 const ovf::VirtualDisk &ovfVdisk = itVirtualDisk->second;
2505
2506 ComObjPtr<Medium> pTargetHD;
2507 importOneDiskImage(ovfDiskImage,
2508 vsdeHD->strVboxCurrent,
2509 pTargetHD,
2510 stack,
2511 pCallbacks,
2512 pStorage);
2513
2514 // now use the new uuid to attach the disk image to our new machine
2515 ComPtr<IMachine> sMachine;
2516 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
2517 if (FAILED(rc)) throw rc;
2518
2519 // find the hard disk controller to which we should attach
2520 ovf::HardDiskController hdc = (*vsysThis.mapControllers.find(ovfVdisk.idController)).second;
2521
2522 // this is for rollback later
2523 MyHardDiskAttachment mhda;
2524 mhda.pMachine = pNewMachine;
2525
2526 convertDiskAttachmentValues(hdc,
2527 ovfVdisk.ulAddressOnParent,
2528 mhda.controllerType, // Bstr
2529 mhda.lControllerPort,
2530 mhda.lDevice);
2531
2532 Log(("Attaching disk %s to port %d on device %d\n", vsdeHD->strVboxCurrent.c_str(), mhda.lControllerPort, mhda.lDevice));
2533
2534 rc = sMachine->AttachDevice(mhda.controllerType.raw(), // wstring name
2535 mhda.lControllerPort, // long controllerPort
2536 mhda.lDevice, // long device
2537 DeviceType_HardDisk, // DeviceType_T type
2538 pTargetHD);
2539 if (FAILED(rc)) throw rc;
2540
2541 stack.llHardDiskAttachments.push_back(mhda);
2542
2543 rc = sMachine->SaveSettings();
2544 if (FAILED(rc)) throw rc;
2545 } // end for (itHD = avsdeHDs.begin();
2546
2547 // only now that we're done with all disks, close the session
2548 rc = stack.pSession->UnlockMachine();
2549 if (FAILED(rc)) throw rc;
2550 stack.fSessionOpen = false;
2551 }
2552 catch(HRESULT /* aRC */)
2553 {
2554 if (stack.fSessionOpen)
2555 stack.pSession->UnlockMachine();
2556
2557 throw;
2558 }
2559 }
2560}
2561
2562/**
2563 * Imports one OVF virtual system (described by a vbox:Machine tag represented by the given config
2564 * structure) into VirtualBox by creating an IMachine instance, which is returned.
2565 *
2566 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
2567 * up any leftovers from this function. For this, the given ImportStack instance has received information
2568 * about what needs cleaning up (to support rollback).
2569 *
2570 * The machine config stored in the settings::MachineConfigFile structure contains the UUIDs of
2571 * the disk attachments used by the machine when it was exported. We also add vbox:uuid attributes
2572 * to the OVF disks sections so we can look them up. While importing these UUIDs into a second host
2573 * will most probably work, reimporting them into the same host will cause conflicts, so we always
2574 * generate new ones on import. This involves the following:
2575 *
2576 * 1) Scan the machine config for disk attachments.
2577 *
2578 * 2) For each disk attachment found, look up the OVF disk image from the disk references section
2579 * and import the disk into VirtualBox, which creates a new UUID for it. In the machine config,
2580 * replace the old UUID with the new one.
2581 *
2582 * 3) Change the machine config according to the OVF virtual system descriptions, in case the
2583 * caller has modified them using setFinalValues().
2584 *
2585 * 4) Create the VirtualBox machine with the modfified machine config.
2586 *
2587 * @param config
2588 * @param pNewMachine
2589 * @param stack
2590 */
2591void Appliance::importVBoxMachine(ComObjPtr<VirtualSystemDescription> &vsdescThis,
2592 ComPtr<IMachine> &pReturnNewMachine,
2593 ImportStack &stack,
2594 PVDINTERFACEIO pCallbacks,
2595 PSHASTORAGE pStorage)
2596{
2597 Assert(vsdescThis->m->pConfig);
2598
2599 HRESULT rc = S_OK;
2600
2601 settings::MachineConfigFile &config = *vsdescThis->m->pConfig;
2602
2603 /*
2604 *
2605 * step 1): modify machine config according to OVF config, in case the user
2606 * has modified them using setFinalValues()
2607 *
2608 */
2609
2610 /* OS Type */
2611 config.machineUserData.strOsType = stack.strOsTypeVBox;
2612 /* Description */
2613 config.machineUserData.strDescription = stack.strDescription;
2614 /* CPU count & extented attributes */
2615 config.hardwareMachine.cCPUs = stack.cCPUs;
2616 if (stack.fForceIOAPIC)
2617 config.hardwareMachine.fHardwareVirt = true;
2618 if (stack.fForceIOAPIC)
2619 config.hardwareMachine.biosSettings.fIOAPICEnabled = true;
2620 /* RAM size */
2621 config.hardwareMachine.ulMemorySizeMB = stack.ulMemorySizeMB;
2622
2623/*
2624 <const name="HardDiskControllerIDE" value="14" />
2625 <const name="HardDiskControllerSATA" value="15" />
2626 <const name="HardDiskControllerSCSI" value="16" />
2627 <const name="HardDiskControllerSAS" value="17" />
2628*/
2629
2630#ifdef VBOX_WITH_USB
2631 /* USB controller */
2632 config.hardwareMachine.usbController.fEnabled = stack.fUSBEnabled;
2633#endif
2634 /* Audio adapter */
2635 if (stack.strAudioAdapter.isNotEmpty())
2636 {
2637 config.hardwareMachine.audioAdapter.fEnabled = true;
2638 config.hardwareMachine.audioAdapter.controllerType = (AudioControllerType_T)stack.strAudioAdapter.toUInt32();
2639 }
2640 else
2641 config.hardwareMachine.audioAdapter.fEnabled = false;
2642 /* Network adapter */
2643 settings::NetworkAdaptersList &llNetworkAdapters = config.hardwareMachine.llNetworkAdapters;
2644 /* First disable all network cards, they will be enabled below again. */
2645 settings::NetworkAdaptersList::iterator it1;
2646 bool fKeepAllMACs = m->optList.contains(ImportOptions_KeepAllMACs);
2647 bool fKeepNATMACs = m->optList.contains(ImportOptions_KeepNATMACs);
2648 for (it1 = llNetworkAdapters.begin(); it1 != llNetworkAdapters.end(); ++it1)
2649 {
2650 it1->fEnabled = false;
2651 if (!( fKeepAllMACs
2652 || (fKeepNATMACs && it1->mode == NetworkAttachmentType_NAT)))
2653 Host::generateMACAddress(it1->strMACAddress);
2654 }
2655 /* Now iterate over all network entries. */
2656 std::list<VirtualSystemDescriptionEntry*> avsdeNWs = vsdescThis->findByType(VirtualSystemDescriptionType_NetworkAdapter);
2657 if (avsdeNWs.size() > 0)
2658 {
2659 /* Iterate through all network adapter entries and search for the
2660 * corresponding one in the machine config. If one is found, configure
2661 * it based on the user settings. */
2662 list<VirtualSystemDescriptionEntry*>::const_iterator itNW;
2663 for (itNW = avsdeNWs.begin();
2664 itNW != avsdeNWs.end();
2665 ++itNW)
2666 {
2667 VirtualSystemDescriptionEntry *vsdeNW = *itNW;
2668 if ( vsdeNW->strExtraConfigCurrent.startsWith("slot=", Utf8Str::CaseInsensitive)
2669 && vsdeNW->strExtraConfigCurrent.length() > 6)
2670 {
2671 uint32_t iSlot = vsdeNW->strExtraConfigCurrent.substr(5, 1).toUInt32();
2672 /* Iterate through all network adapters in the machine config. */
2673 for (it1 = llNetworkAdapters.begin();
2674 it1 != llNetworkAdapters.end();
2675 ++it1)
2676 {
2677 /* Compare the slots. */
2678 if (it1->ulSlot == iSlot)
2679 {
2680 it1->fEnabled = true;
2681 it1->type = (NetworkAdapterType_T)vsdeNW->strVboxCurrent.toUInt32();
2682 break;
2683 }
2684 }
2685 }
2686 }
2687 }
2688
2689 /* Floppy controller */
2690 bool fFloppy = vsdescThis->findByType(VirtualSystemDescriptionType_Floppy).size() > 0;
2691 /* DVD controller */
2692 bool fDVD = vsdescThis->findByType(VirtualSystemDescriptionType_CDROM).size() > 0;
2693 /* Iterate over all storage controller check the attachments and remove
2694 * them when necessary. Also detect broken configs with more than one
2695 * attachment. Old VirtualBox versions (prior to 3.2.10) had all disk
2696 * attachments pointing to the last hard disk image, which causes import
2697 * failures. A long fixed bug, however the OVF files are long lived. */
2698 settings::StorageControllersList &llControllers = config.storageMachine.llStorageControllers;
2699 Guid hdUuid;
2700 uint32_t cHardDisks = 0;
2701 bool fInconsistent = false;
2702 bool fRepairDuplicate = false;
2703 settings::StorageControllersList::iterator it3;
2704 for (it3 = llControllers.begin();
2705 it3 != llControllers.end();
2706 ++it3)
2707 {
2708 settings::AttachedDevicesList &llAttachments = it3->llAttachedDevices;
2709 settings::AttachedDevicesList::iterator it4 = llAttachments.begin();
2710 while (it4 != llAttachments.end())
2711 {
2712 if ( ( !fDVD
2713 && it4->deviceType == DeviceType_DVD)
2714 ||
2715 ( !fFloppy
2716 && it4->deviceType == DeviceType_Floppy))
2717 {
2718 it4 = llAttachments.erase(it4);
2719 continue;
2720 }
2721 else if (it4->deviceType == DeviceType_HardDisk)
2722 {
2723 const Guid &thisUuid = it4->uuid;
2724 cHardDisks++;
2725 if (cHardDisks == 1)
2726 {
2727 if (hdUuid.isZero())
2728 hdUuid = thisUuid;
2729 else
2730 fInconsistent = true;
2731 }
2732 else
2733 {
2734 if (thisUuid.isZero())
2735 fInconsistent = true;
2736 else if (thisUuid == hdUuid)
2737 fRepairDuplicate = true;
2738 }
2739 }
2740 ++it4;
2741 }
2742 }
2743 /* paranoia... */
2744 if (fInconsistent || cHardDisks == 1)
2745 fRepairDuplicate = false;
2746
2747 /*
2748 *
2749 * step 2: scan the machine config for media attachments
2750 *
2751 */
2752
2753 /* Get all hard disk descriptions. */
2754 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
2755 std::list<VirtualSystemDescriptionEntry*>::iterator avsdeHDsIt = avsdeHDs.begin();
2756 /* paranoia - if there is no 1:1 match do not try to repair. */
2757 if (cHardDisks != avsdeHDs.size())
2758 fRepairDuplicate = false;
2759
2760 // for each storage controller...
2761 for (settings::StorageControllersList::iterator sit = config.storageMachine.llStorageControllers.begin();
2762 sit != config.storageMachine.llStorageControllers.end();
2763 ++sit)
2764 {
2765 settings::StorageController &sc = *sit;
2766
2767 // find the OVF virtual system description entry for this storage controller
2768 switch (sc.storageBus)
2769 {
2770 case StorageBus_SATA:
2771 break;
2772 case StorageBus_SCSI:
2773 break;
2774 case StorageBus_IDE:
2775 break;
2776 case StorageBus_SAS:
2777 break;
2778 }
2779
2780 // for each medium attachment to this controller...
2781 for (settings::AttachedDevicesList::iterator dit = sc.llAttachedDevices.begin();
2782 dit != sc.llAttachedDevices.end();
2783 ++dit)
2784 {
2785 settings::AttachedDevice &d = *dit;
2786
2787 if (d.uuid.isZero())
2788 // empty DVD and floppy media
2789 continue;
2790
2791 // When repairing a broken VirtualBox xml config section (written
2792 // by VirtualBox versions earlier than 3.2.10) assume the disks
2793 // show up in the same order as in the OVF description.
2794 if (fRepairDuplicate)
2795 {
2796 VirtualSystemDescriptionEntry *vsdeHD = *avsdeHDsIt;
2797 ovf::DiskImagesMap::const_iterator itDiskImage = stack.mapDisks.find(vsdeHD->strRef);
2798 if (itDiskImage != stack.mapDisks.end())
2799 {
2800 const ovf::DiskImage &di = itDiskImage->second;
2801 d.uuid = Guid(di.uuidVbox);
2802 }
2803 ++avsdeHDsIt;
2804 }
2805
2806 // convert the Guid to string
2807 Utf8Str strUuid = d.uuid.toString();
2808
2809 // there must be an image in the OVF disk structs with the same UUID
2810 bool fFound = false;
2811 for (ovf::DiskImagesMap::const_iterator oit = stack.mapDisks.begin();
2812 oit != stack.mapDisks.end();
2813 ++oit)
2814 {
2815 const ovf::DiskImage &di = oit->second;
2816
2817 if (di.uuidVbox == strUuid)
2818 {
2819 VirtualSystemDescriptionEntry *vsdeTargetHD = 0;
2820
2821 /* Iterate over all given disk images of the virtual system
2822 * disks description. We need to find the target disk path,
2823 * which could be changed by the user. */
2824 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
2825 for (itHD = avsdeHDs.begin();
2826 itHD != avsdeHDs.end();
2827 ++itHD)
2828 {
2829 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
2830 if (vsdeHD->strRef == oit->first)
2831 {
2832 vsdeTargetHD = vsdeHD;
2833 break;
2834 }
2835 }
2836 if (!vsdeTargetHD)
2837 throw setError(E_FAIL,
2838 tr("Internal inconsistency looking up disk image '%s'"),
2839 oit->first.c_str());
2840
2841 /*
2842 *
2843 * step 3: import disk
2844 *
2845 */
2846 ComObjPtr<Medium> pTargetHD;
2847 importOneDiskImage(di,
2848 vsdeTargetHD->strVboxCurrent,
2849 pTargetHD,
2850 stack,
2851 pCallbacks,
2852 pStorage);
2853
2854 // ... and replace the old UUID in the machine config with the one of
2855 // the imported disk that was just created
2856 Bstr hdId;
2857 rc = pTargetHD->COMGETTER(Id)(hdId.asOutParam());
2858 if (FAILED(rc)) throw rc;
2859
2860 d.uuid = hdId;
2861
2862 fFound = true;
2863 break;
2864 }
2865 }
2866
2867 // no disk with such a UUID found:
2868 if (!fFound)
2869 throw setError(E_FAIL,
2870 tr("<vbox:Machine> element in OVF contains a medium attachment for the disk image %s but the OVF describes no such image"),
2871 strUuid.c_str());
2872 } // for (settings::AttachedDevicesList::const_iterator dit = sc.llAttachedDevices.begin();
2873 } // for (settings::StorageControllersList::const_iterator sit = config.storageMachine.llStorageControllers.begin();
2874
2875 /*
2876 *
2877 * step 4): create the machine and have it import the config
2878 *
2879 */
2880
2881 ComObjPtr<Machine> pNewMachine;
2882 rc = pNewMachine.createObject();
2883 if (FAILED(rc)) throw rc;
2884
2885 // this magic constructor fills the new machine object with the MachineConfig
2886 // instance that we created from the vbox:Machine
2887 rc = pNewMachine->init(mVirtualBox,
2888 stack.strNameVBox, // name from OVF preparations; can be suffixed to avoid duplicates, or changed by user
2889 config); // the whole machine config
2890 if (FAILED(rc)) throw rc;
2891
2892 pReturnNewMachine = ComPtr<IMachine>(pNewMachine);
2893
2894 // and register it
2895 rc = mVirtualBox->RegisterMachine(pNewMachine);
2896 if (FAILED(rc)) throw rc;
2897
2898 // store new machine for roll-back in case of errors
2899 Bstr bstrNewMachineId;
2900 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
2901 if (FAILED(rc)) throw rc;
2902 m->llGuidsMachinesCreated.push_back(Guid(bstrNewMachineId));
2903}
2904
2905void Appliance::importMachines(ImportStack &stack,
2906 PVDINTERFACEIO pCallbacks,
2907 PSHASTORAGE pStorage)
2908{
2909 HRESULT rc = S_OK;
2910
2911 // this is safe to access because this thread only gets started
2912 // if pReader != NULL
2913 const ovf::OVFReader &reader = *m->pReader;
2914 const ovf::OVFVersion_T ovfVersion = reader.m_envelopeData.getOVFVersion();
2915
2916 if ( ovfVersion == ovf::OVFVersion_2_0)
2917 pStorage->fSha256 = true;
2918
2919 // create a session for the machine + disks we manipulate below
2920 rc = stack.pSession.createInprocObject(CLSID_Session);
2921 if (FAILED(rc)) throw rc;
2922
2923 list<ovf::VirtualSystem>::const_iterator it;
2924 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it1;
2925 /* Iterate through all virtual systems of that appliance */
2926 size_t i = 0;
2927 for (it = reader.m_llVirtualSystems.begin(),
2928 it1 = m->virtualSystemDescriptions.begin();
2929 it != reader.m_llVirtualSystems.end();
2930 ++it, ++it1, ++i)
2931 {
2932 const ovf::VirtualSystem &vsysThis = *it;
2933 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it1);
2934
2935 ComPtr<IMachine> pNewMachine;
2936
2937 // there are two ways in which we can create a vbox machine from OVF:
2938 // -- either this OVF was written by vbox 3.2 or later, in which case there is a <vbox:Machine> element
2939 // in the <VirtualSystem>; then the VirtualSystemDescription::Data has a settings::MachineConfigFile
2940 // with all the machine config pretty-parsed;
2941 // -- or this is an OVF from an older vbox or an external source, and then we need to translate the
2942 // VirtualSystemDescriptionEntry and do import work
2943
2944 // Even for the vbox:Machine case, there are a number of configuration items that will be taken from
2945 // the OVF because otherwise the "override import parameters" mechanism in the GUI won't work.
2946
2947 // VM name
2948 std::list<VirtualSystemDescriptionEntry*> vsdeName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
2949 if (vsdeName.size() < 1)
2950 throw setError(VBOX_E_FILE_ERROR,
2951 tr("Missing VM name"));
2952 stack.strNameVBox = vsdeName.front()->strVboxCurrent;
2953
2954 // have VirtualBox suggest where the filename would be placed so we can
2955 // put the disk images in the same directory
2956 Bstr bstrMachineFilename;
2957 rc = mVirtualBox->ComposeMachineFilename(Bstr(stack.strNameVBox).raw(),
2958 NULL /* aGroup */,
2959 NULL /* aCreateFlags */,
2960 NULL /* aBaseFolder */,
2961 bstrMachineFilename.asOutParam());
2962 if (FAILED(rc)) throw rc;
2963 // and determine the machine folder from that
2964 stack.strMachineFolder = bstrMachineFilename;
2965 stack.strMachineFolder.stripFilename();
2966
2967 // guest OS type
2968 std::list<VirtualSystemDescriptionEntry*> vsdeOS;
2969 vsdeOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
2970 if (vsdeOS.size() < 1)
2971 throw setError(VBOX_E_FILE_ERROR,
2972 tr("Missing guest OS type"));
2973 stack.strOsTypeVBox = vsdeOS.front()->strVboxCurrent;
2974
2975 // CPU count
2976 std::list<VirtualSystemDescriptionEntry*> vsdeCPU = vsdescThis->findByType(VirtualSystemDescriptionType_CPU);
2977 if (vsdeCPU.size() != 1)
2978 throw setError(VBOX_E_FILE_ERROR, tr("CPU count missing"));
2979
2980 stack.cCPUs = vsdeCPU.front()->strVboxCurrent.toUInt32();
2981 // We need HWVirt & IO-APIC if more than one CPU is requested
2982 if (stack.cCPUs > 1)
2983 {
2984 stack.fForceHWVirt = true;
2985 stack.fForceIOAPIC = true;
2986 }
2987
2988 // RAM
2989 std::list<VirtualSystemDescriptionEntry*> vsdeRAM = vsdescThis->findByType(VirtualSystemDescriptionType_Memory);
2990 if (vsdeRAM.size() != 1)
2991 throw setError(VBOX_E_FILE_ERROR, tr("RAM size missing"));
2992 stack.ulMemorySizeMB = (ULONG)vsdeRAM.front()->strVboxCurrent.toUInt64();
2993
2994#ifdef VBOX_WITH_USB
2995 // USB controller
2996 std::list<VirtualSystemDescriptionEntry*> vsdeUSBController = vsdescThis->findByType(VirtualSystemDescriptionType_USBController);
2997 // USB support is enabled if there's at least one such entry; to disable USB support,
2998 // the type of the USB item would have been changed to "ignore"
2999 stack.fUSBEnabled = vsdeUSBController.size() > 0;
3000#endif
3001 // audio adapter
3002 std::list<VirtualSystemDescriptionEntry*> vsdeAudioAdapter = vsdescThis->findByType(VirtualSystemDescriptionType_SoundCard);
3003 /* @todo: we support one audio adapter only */
3004 if (vsdeAudioAdapter.size() > 0)
3005 stack.strAudioAdapter = vsdeAudioAdapter.front()->strVboxCurrent;
3006
3007 // for the description of the new machine, always use the OVF entry, the user may have changed it in the import config
3008 std::list<VirtualSystemDescriptionEntry*> vsdeDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
3009 if (vsdeDescription.size())
3010 stack.strDescription = vsdeDescription.front()->strVboxCurrent;
3011
3012 // import vbox:machine or OVF now
3013 if (vsdescThis->m->pConfig)
3014 // vbox:Machine config
3015 importVBoxMachine(vsdescThis, pNewMachine, stack, pCallbacks, pStorage);
3016 else
3017 // generic OVF config
3018 importMachineGeneric(vsysThis, vsdescThis, pNewMachine, stack, pCallbacks, pStorage);
3019
3020 } // for (it = pAppliance->m->llVirtualSystems.begin() ...
3021}
3022
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