VirtualBox

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

Last change on this file since 46860 was 46754, checked in by vboxsync, 11 years ago

small typo was fixed.

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

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