VirtualBox

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

Last change on this file since 59671 was 59671, checked in by vboxsync, 9 years ago

Main: Appliance::i_readTailProcessing: Sketched out how to validate certificates that aren't self-signed. Currently untested.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 168.4 KB
Line 
1/* $Id: ApplianceImplImport.cpp 59671 2016-02-15 02:00:04Z vboxsync $ */
2/** @file
3 * IAppliance and IVirtualSystem COM class implementations.
4 */
5
6/*
7 * Copyright (C) 2008-2016 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#include <iprt/alloca.h>
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/zip.h>
27#include <iprt/stream.h>
28#include <iprt/crypto/digest.h>
29#include <iprt/crypto/pkix.h>
30#include <iprt/crypto/store.h>
31#include <iprt/crypto/x509.h>
32
33#include <VBox/vd.h>
34#include <VBox/com/array.h>
35
36#include "ApplianceImpl.h"
37#include "VirtualBoxImpl.h"
38#include "GuestOSTypeImpl.h"
39#include "ProgressImpl.h"
40#include "MachineImpl.h"
41#include "MediumImpl.h"
42#include "MediumFormatImpl.h"
43#include "SystemPropertiesImpl.h"
44#include "HostImpl.h"
45
46#include "AutoCaller.h"
47#include "Logging.h"
48
49#include "ApplianceImplPrivate.h"
50
51#include <VBox/param.h>
52#include <VBox/version.h>
53#include <VBox/settings.h>
54
55#include <set>
56
57using namespace std;
58
59////////////////////////////////////////////////////////////////////////////////
60//
61// IAppliance public methods
62//
63////////////////////////////////////////////////////////////////////////////////
64
65/**
66 * Public method implementation. This opens the OVF with ovfreader.cpp.
67 * Thread implementation is in Appliance::readImpl().
68 *
69 * @param aFile
70 * @return
71 */
72HRESULT Appliance::read(const com::Utf8Str &aFile,
73 ComPtr<IProgress> &aProgress)
74{
75 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
76
77 if (!i_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 if ( !aFile.endsWith(".ovf", Utf8Str::CaseInsensitive)
88 && !aFile.endsWith(".ova", Utf8Str::CaseInsensitive))
89 return setError(VBOX_E_FILE_ERROR, tr("Appliance file must have .ovf or .ova extension"));
90
91 ComObjPtr<Progress> progress;
92 try
93 {
94 /* Parse all necessary info out of the URI */
95 i_parseURI(aFile, m->locInfo);
96 i_readImpl(m->locInfo, progress);
97 }
98 catch (HRESULT aRC)
99 {
100 return aRC;
101 }
102
103 /* Return progress to the caller */
104 progress.queryInterfaceTo(aProgress.asOutParam());
105 return S_OK;
106}
107
108/**
109 * Public method implementation. This looks at the output of ovfreader.cpp and creates
110 * VirtualSystemDescription instances.
111 * @return
112 */
113HRESULT Appliance::interpret()
114{
115 // @todo:
116 // - don't use COM methods but the methods directly (faster, but needs appropriate
117 // locking of that objects itself (s. HardDisk))
118 // - Appropriate handle errors like not supported file formats
119 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
120
121 if (!i_isApplianceIdle())
122 return E_ACCESSDENIED;
123
124 HRESULT rc = S_OK;
125
126 /* Clear any previous virtual system descriptions */
127 m->virtualSystemDescriptions.clear();
128
129 if (!m->pReader)
130 return setError(E_FAIL,
131 tr("Cannot interpret appliance without reading it first (call read() before interpret())"));
132
133 // Change the appliance state so we can safely leave the lock while doing time-consuming
134 // disk imports; also the below method calls do all kinds of locking which conflicts with
135 // the appliance object lock
136 m->state = Data::ApplianceImporting;
137 alock.release();
138
139 /* Try/catch so we can clean up on error */
140 try
141 {
142 list<ovf::VirtualSystem>::const_iterator it;
143 /* Iterate through all virtual systems */
144 for (it = m->pReader->m_llVirtualSystems.begin();
145 it != m->pReader->m_llVirtualSystems.end();
146 ++it)
147 {
148 const ovf::VirtualSystem &vsysThis = *it;
149
150 ComObjPtr<VirtualSystemDescription> pNewDesc;
151 rc = pNewDesc.createObject();
152 if (FAILED(rc)) throw rc;
153 rc = pNewDesc->init();
154 if (FAILED(rc)) throw rc;
155
156 // if the virtual system in OVF had a <vbox:Machine> element, have the
157 // VirtualBox settings code parse that XML now
158 if (vsysThis.pelmVBoxMachine)
159 pNewDesc->i_importVBoxMachineXML(*vsysThis.pelmVBoxMachine);
160
161 // Guest OS type
162 // This is taken from one of three places, in this order:
163 Utf8Str strOsTypeVBox;
164 Utf8StrFmt strCIMOSType("%RU32", (uint32_t)vsysThis.cimos);
165 // 1) If there is a <vbox:Machine>, then use the type from there.
166 if ( vsysThis.pelmVBoxMachine
167 && pNewDesc->m->pConfig->machineUserData.strOsType.isNotEmpty()
168 )
169 strOsTypeVBox = pNewDesc->m->pConfig->machineUserData.strOsType;
170 // 2) Otherwise, if there is OperatingSystemSection/vbox:OSType, use that one.
171 else if (vsysThis.strTypeVBox.isNotEmpty()) // OVFReader has found vbox:OSType
172 strOsTypeVBox = vsysThis.strTypeVBox;
173 // 3) Otherwise, make a best guess what the vbox type is from the OVF (CIM) OS type.
174 else
175 convertCIMOSType2VBoxOSType(strOsTypeVBox, vsysThis.cimos, vsysThis.strCimosDesc);
176 pNewDesc->i_addEntry(VirtualSystemDescriptionType_OS,
177 "",
178 strCIMOSType,
179 strOsTypeVBox);
180
181 /* VM name */
182 Utf8Str nameVBox;
183 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
184 if ( vsysThis.pelmVBoxMachine
185 && pNewDesc->m->pConfig->machineUserData.strName.isNotEmpty())
186 nameVBox = pNewDesc->m->pConfig->machineUserData.strName;
187 else
188 nameVBox = vsysThis.strName;
189 /* If there isn't any name specified create a default one out
190 * of the OS type */
191 if (nameVBox.isEmpty())
192 nameVBox = strOsTypeVBox;
193 i_searchUniqueVMName(nameVBox);
194 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Name,
195 "",
196 vsysThis.strName,
197 nameVBox);
198
199 /* Based on the VM name, create a target machine path. */
200 Bstr bstrMachineFilename;
201 rc = mVirtualBox->ComposeMachineFilename(Bstr(nameVBox).raw(),
202 NULL /* aGroup */,
203 NULL /* aCreateFlags */,
204 NULL /* aBaseFolder */,
205 bstrMachineFilename.asOutParam());
206 if (FAILED(rc)) throw rc;
207 /* Determine the machine folder from that */
208 Utf8Str strMachineFolder = Utf8Str(bstrMachineFilename).stripFilename();
209
210 /* VM Product */
211 if (!vsysThis.strProduct.isEmpty())
212 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Product,
213 "",
214 vsysThis.strProduct,
215 vsysThis.strProduct);
216
217 /* VM Vendor */
218 if (!vsysThis.strVendor.isEmpty())
219 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Vendor,
220 "",
221 vsysThis.strVendor,
222 vsysThis.strVendor);
223
224 /* VM Version */
225 if (!vsysThis.strVersion.isEmpty())
226 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Version,
227 "",
228 vsysThis.strVersion,
229 vsysThis.strVersion);
230
231 /* VM ProductUrl */
232 if (!vsysThis.strProductUrl.isEmpty())
233 pNewDesc->i_addEntry(VirtualSystemDescriptionType_ProductUrl,
234 "",
235 vsysThis.strProductUrl,
236 vsysThis.strProductUrl);
237
238 /* VM VendorUrl */
239 if (!vsysThis.strVendorUrl.isEmpty())
240 pNewDesc->i_addEntry(VirtualSystemDescriptionType_VendorUrl,
241 "",
242 vsysThis.strVendorUrl,
243 vsysThis.strVendorUrl);
244
245 /* VM description */
246 if (!vsysThis.strDescription.isEmpty())
247 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Description,
248 "",
249 vsysThis.strDescription,
250 vsysThis.strDescription);
251
252 /* VM license */
253 if (!vsysThis.strLicenseText.isEmpty())
254 pNewDesc->i_addEntry(VirtualSystemDescriptionType_License,
255 "",
256 vsysThis.strLicenseText,
257 vsysThis.strLicenseText);
258
259 /* Now that we know the OS type, get our internal defaults based on that. */
260 ComPtr<IGuestOSType> pGuestOSType;
261 rc = mVirtualBox->GetGuestOSType(Bstr(strOsTypeVBox).raw(), pGuestOSType.asOutParam());
262 if (FAILED(rc)) throw rc;
263
264 /* CPU count */
265 ULONG cpuCountVBox;
266 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
267 if ( vsysThis.pelmVBoxMachine
268 && pNewDesc->m->pConfig->hardwareMachine.cCPUs)
269 cpuCountVBox = pNewDesc->m->pConfig->hardwareMachine.cCPUs;
270 else
271 cpuCountVBox = vsysThis.cCPUs;
272 /* Check for the constraints */
273 if (cpuCountVBox > SchemaDefs::MaxCPUCount)
274 {
275 i_addWarning(tr("The virtual system \"%s\" claims support for %u CPU's, but VirtualBox has support for "
276 "max %u CPU's only."),
277 vsysThis.strName.c_str(), cpuCountVBox, SchemaDefs::MaxCPUCount);
278 cpuCountVBox = SchemaDefs::MaxCPUCount;
279 }
280 if (vsysThis.cCPUs == 0)
281 cpuCountVBox = 1;
282 pNewDesc->i_addEntry(VirtualSystemDescriptionType_CPU,
283 "",
284 Utf8StrFmt("%RU32", (uint32_t)vsysThis.cCPUs),
285 Utf8StrFmt("%RU32", (uint32_t)cpuCountVBox));
286
287 /* RAM */
288 uint64_t ullMemSizeVBox;
289 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
290 if ( vsysThis.pelmVBoxMachine
291 && pNewDesc->m->pConfig->hardwareMachine.ulMemorySizeMB)
292 ullMemSizeVBox = pNewDesc->m->pConfig->hardwareMachine.ulMemorySizeMB;
293 else
294 ullMemSizeVBox = vsysThis.ullMemorySize / _1M;
295 /* Check for the constraints */
296 if ( ullMemSizeVBox != 0
297 && ( ullMemSizeVBox < MM_RAM_MIN_IN_MB
298 || ullMemSizeVBox > MM_RAM_MAX_IN_MB
299 )
300 )
301 {
302 i_addWarning(tr("The virtual system \"%s\" claims support for %llu MB RAM size, but VirtualBox has "
303 "support for min %u & max %u MB RAM size only."),
304 vsysThis.strName.c_str(), ullMemSizeVBox, MM_RAM_MIN_IN_MB, MM_RAM_MAX_IN_MB);
305 ullMemSizeVBox = RT_MIN(RT_MAX(ullMemSizeVBox, MM_RAM_MIN_IN_MB), MM_RAM_MAX_IN_MB);
306 }
307 if (vsysThis.ullMemorySize == 0)
308 {
309 /* If the RAM of the OVF is zero, use our predefined values */
310 ULONG memSizeVBox2;
311 rc = pGuestOSType->COMGETTER(RecommendedRAM)(&memSizeVBox2);
312 if (FAILED(rc)) throw rc;
313 /* VBox stores that in MByte */
314 ullMemSizeVBox = (uint64_t)memSizeVBox2;
315 }
316 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Memory,
317 "",
318 Utf8StrFmt("%RU64", (uint64_t)vsysThis.ullMemorySize),
319 Utf8StrFmt("%RU64", (uint64_t)ullMemSizeVBox));
320
321 /* Audio */
322 Utf8Str strSoundCard;
323 Utf8Str strSoundCardOrig;
324 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
325 if ( vsysThis.pelmVBoxMachine
326 && pNewDesc->m->pConfig->hardwareMachine.audioAdapter.fEnabled)
327 {
328 strSoundCard = Utf8StrFmt("%RU32",
329 (uint32_t)pNewDesc->m->pConfig->hardwareMachine.audioAdapter.controllerType);
330 }
331 else if (vsysThis.strSoundCardType.isNotEmpty())
332 {
333 /* Set the AC97 always for the simple OVF case.
334 * @todo: figure out the hardware which could be possible */
335 strSoundCard = Utf8StrFmt("%RU32", (uint32_t)AudioControllerType_AC97);
336 strSoundCardOrig = vsysThis.strSoundCardType;
337 }
338 if (strSoundCard.isNotEmpty())
339 pNewDesc->i_addEntry(VirtualSystemDescriptionType_SoundCard,
340 "",
341 strSoundCardOrig,
342 strSoundCard);
343
344#ifdef VBOX_WITH_USB
345 /* USB Controller */
346 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
347 if ( ( vsysThis.pelmVBoxMachine
348 && pNewDesc->m->pConfig->hardwareMachine.usbSettings.llUSBControllers.size() > 0)
349 || vsysThis.fHasUsbController)
350 pNewDesc->i_addEntry(VirtualSystemDescriptionType_USBController, "", "", "");
351#endif /* VBOX_WITH_USB */
352
353 /* Network Controller */
354 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
355 if (vsysThis.pelmVBoxMachine)
356 {
357 uint32_t maxNetworkAdapters = Global::getMaxNetworkAdapters(pNewDesc->m->pConfig->hardwareMachine.chipsetType);
358
359 const settings::NetworkAdaptersList &llNetworkAdapters = pNewDesc->m->pConfig->hardwareMachine.llNetworkAdapters;
360 /* Check for the constrains */
361 if (llNetworkAdapters.size() > maxNetworkAdapters)
362 i_addWarning(tr("The virtual system \"%s\" claims support for %zu network adapters, but VirtualBox "
363 "has support for max %u network adapter only."),
364 vsysThis.strName.c_str(), llNetworkAdapters.size(), maxNetworkAdapters);
365 /* Iterate through all network adapters. */
366 settings::NetworkAdaptersList::const_iterator it1;
367 size_t a = 0;
368 for (it1 = llNetworkAdapters.begin();
369 it1 != llNetworkAdapters.end() && a < maxNetworkAdapters;
370 ++it1, ++a)
371 {
372 if (it1->fEnabled)
373 {
374 Utf8Str strMode = convertNetworkAttachmentTypeToString(it1->mode);
375 pNewDesc->i_addEntry(VirtualSystemDescriptionType_NetworkAdapter,
376 "", // ref
377 strMode, // orig
378 Utf8StrFmt("%RU32", (uint32_t)it1->type), // conf
379 0,
380 Utf8StrFmt("slot=%RU32;type=%s", it1->ulSlot, strMode.c_str())); // extra conf
381 }
382 }
383 }
384 /* else we use the ovf configuration. */
385 else if (vsysThis.llEthernetAdapters.size() > 0)
386 {
387 size_t cEthernetAdapters = vsysThis.llEthernetAdapters.size();
388 uint32_t maxNetworkAdapters = Global::getMaxNetworkAdapters(ChipsetType_PIIX3);
389
390 /* Check for the constrains */
391 if (cEthernetAdapters > maxNetworkAdapters)
392 i_addWarning(tr("The virtual system \"%s\" claims support for %zu network adapters, but VirtualBox "
393 "has support for max %u network adapter only."),
394 vsysThis.strName.c_str(), cEthernetAdapters, maxNetworkAdapters);
395
396 /* Get the default network adapter type for the selected guest OS */
397 NetworkAdapterType_T defaultAdapterVBox = NetworkAdapterType_Am79C970A;
398 rc = pGuestOSType->COMGETTER(AdapterType)(&defaultAdapterVBox);
399 if (FAILED(rc)) throw rc;
400
401 ovf::EthernetAdaptersList::const_iterator itEA;
402 /* Iterate through all abstract networks. Ignore network cards
403 * which exceed the limit of VirtualBox. */
404 size_t a = 0;
405 for (itEA = vsysThis.llEthernetAdapters.begin();
406 itEA != vsysThis.llEthernetAdapters.end() && a < maxNetworkAdapters;
407 ++itEA, ++a)
408 {
409 const ovf::EthernetAdapter &ea = *itEA; // logical network to connect to
410 Utf8Str strNetwork = ea.strNetworkName;
411 // make sure it's one of these two
412 if ( (strNetwork.compare("Null", Utf8Str::CaseInsensitive))
413 && (strNetwork.compare("NAT", Utf8Str::CaseInsensitive))
414 && (strNetwork.compare("Bridged", Utf8Str::CaseInsensitive))
415 && (strNetwork.compare("Internal", Utf8Str::CaseInsensitive))
416 && (strNetwork.compare("HostOnly", Utf8Str::CaseInsensitive))
417 && (strNetwork.compare("Generic", Utf8Str::CaseInsensitive))
418 )
419 strNetwork = "Bridged"; // VMware assumes this is the default apparently
420
421 /* Figure out the hardware type */
422 NetworkAdapterType_T nwAdapterVBox = defaultAdapterVBox;
423 if (!ea.strAdapterType.compare("PCNet32", Utf8Str::CaseInsensitive))
424 {
425 /* If the default adapter is already one of the two
426 * PCNet adapters use the default one. If not use the
427 * Am79C970A as fallback. */
428 if (!(defaultAdapterVBox == NetworkAdapterType_Am79C970A ||
429 defaultAdapterVBox == NetworkAdapterType_Am79C973))
430 nwAdapterVBox = NetworkAdapterType_Am79C970A;
431 }
432#ifdef VBOX_WITH_E1000
433 /* VMWare accidentally write this with VirtualCenter 3.5,
434 so make sure in this case always to use the VMWare one */
435 else if (!ea.strAdapterType.compare("E10000", Utf8Str::CaseInsensitive))
436 nwAdapterVBox = NetworkAdapterType_I82545EM;
437 else if (!ea.strAdapterType.compare("E1000", Utf8Str::CaseInsensitive))
438 {
439 /* Check if this OVF was written by VirtualBox */
440 if (Utf8Str(vsysThis.strVirtualSystemType).contains("virtualbox", Utf8Str::CaseInsensitive))
441 {
442 /* If the default adapter is already one of the three
443 * E1000 adapters use the default one. If not use the
444 * I82545EM as fallback. */
445 if (!(defaultAdapterVBox == NetworkAdapterType_I82540EM ||
446 defaultAdapterVBox == NetworkAdapterType_I82543GC ||
447 defaultAdapterVBox == NetworkAdapterType_I82545EM))
448 nwAdapterVBox = NetworkAdapterType_I82540EM;
449 }
450 else
451 /* Always use this one since it's what VMware uses */
452 nwAdapterVBox = NetworkAdapterType_I82545EM;
453 }
454#endif /* VBOX_WITH_E1000 */
455
456 pNewDesc->i_addEntry(VirtualSystemDescriptionType_NetworkAdapter,
457 "", // ref
458 ea.strNetworkName, // orig
459 Utf8StrFmt("%RU32", (uint32_t)nwAdapterVBox), // conf
460 0,
461 Utf8StrFmt("type=%s", strNetwork.c_str())); // extra conf
462 }
463 }
464
465 /* If there is a <vbox:Machine>, we always prefer the setting from there. */
466 bool fFloppy = false;
467 bool fDVD = false;
468 if (vsysThis.pelmVBoxMachine)
469 {
470 settings::StorageControllersList &llControllers = pNewDesc->m->pConfig->storageMachine.llStorageControllers;
471 settings::StorageControllersList::iterator it3;
472 for (it3 = llControllers.begin();
473 it3 != llControllers.end();
474 ++it3)
475 {
476 settings::AttachedDevicesList &llAttachments = it3->llAttachedDevices;
477 settings::AttachedDevicesList::iterator it4;
478 for (it4 = llAttachments.begin();
479 it4 != llAttachments.end();
480 ++it4)
481 {
482 fDVD |= it4->deviceType == DeviceType_DVD;
483 fFloppy |= it4->deviceType == DeviceType_Floppy;
484 if (fFloppy && fDVD)
485 break;
486 }
487 if (fFloppy && fDVD)
488 break;
489 }
490 }
491 else
492 {
493 fFloppy = vsysThis.fHasFloppyDrive;
494 fDVD = vsysThis.fHasCdromDrive;
495 }
496 /* Floppy Drive */
497 if (fFloppy)
498 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Floppy, "", "", "");
499 /* CD Drive */
500 if (fDVD)
501 pNewDesc->i_addEntry(VirtualSystemDescriptionType_CDROM, "", "", "");
502
503 /* Hard disk Controller */
504 uint16_t cIDEused = 0;
505 uint16_t cSATAused = 0; NOREF(cSATAused);
506 uint16_t cSCSIused = 0; NOREF(cSCSIused);
507 ovf::ControllersMap::const_iterator hdcIt;
508 /* Iterate through all hard disk controllers */
509 for (hdcIt = vsysThis.mapControllers.begin();
510 hdcIt != vsysThis.mapControllers.end();
511 ++hdcIt)
512 {
513 const ovf::HardDiskController &hdc = hdcIt->second;
514 Utf8Str strControllerID = Utf8StrFmt("%RI32", (uint32_t)hdc.idController);
515
516 switch (hdc.system)
517 {
518 case ovf::HardDiskController::IDE:
519 /* Check for the constrains */
520 if (cIDEused < 4)
521 {
522 // @todo: figure out the IDE types
523 /* Use PIIX4 as default */
524 Utf8Str strType = "PIIX4";
525 if (!hdc.strControllerType.compare("PIIX3", Utf8Str::CaseInsensitive))
526 strType = "PIIX3";
527 else if (!hdc.strControllerType.compare("ICH6", Utf8Str::CaseInsensitive))
528 strType = "ICH6";
529 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
530 strControllerID, // strRef
531 hdc.strControllerType, // aOvfValue
532 strType); // aVBoxValue
533 }
534 else
535 /* Warn only once */
536 if (cIDEused == 2)
537 i_addWarning(tr("The virtual \"%s\" system requests support for more than two "
538 "IDE controller channels, but VirtualBox supports only two."),
539 vsysThis.strName.c_str());
540
541 ++cIDEused;
542 break;
543
544 case ovf::HardDiskController::SATA:
545 /* Check for the constrains */
546 if (cSATAused < 1)
547 {
548 // @todo: figure out the SATA types
549 /* We only support a plain AHCI controller, so use them always */
550 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerSATA,
551 strControllerID,
552 hdc.strControllerType,
553 "AHCI");
554 }
555 else
556 {
557 /* Warn only once */
558 if (cSATAused == 1)
559 i_addWarning(tr("The virtual system \"%s\" requests support for more than one "
560 "SATA controller, but VirtualBox has support for only one"),
561 vsysThis.strName.c_str());
562
563 }
564 ++cSATAused;
565 break;
566
567 case ovf::HardDiskController::SCSI:
568 /* Check for the constrains */
569 if (cSCSIused < 1)
570 {
571 VirtualSystemDescriptionType_T vsdet = VirtualSystemDescriptionType_HardDiskControllerSCSI;
572 Utf8Str hdcController = "LsiLogic";
573 if (!hdc.strControllerType.compare("lsilogicsas", Utf8Str::CaseInsensitive))
574 {
575 // OVF considers SAS a variant of SCSI but VirtualBox considers it a class of its own
576 vsdet = VirtualSystemDescriptionType_HardDiskControllerSAS;
577 hdcController = "LsiLogicSas";
578 }
579 else if (!hdc.strControllerType.compare("BusLogic", Utf8Str::CaseInsensitive))
580 hdcController = "BusLogic";
581 pNewDesc->i_addEntry(vsdet,
582 strControllerID,
583 hdc.strControllerType,
584 hdcController);
585 }
586 else
587 i_addWarning(tr("The virtual system \"%s\" requests support for an additional "
588 "SCSI controller of type \"%s\" with ID %s, but VirtualBox presently "
589 "supports only one SCSI controller."),
590 vsysThis.strName.c_str(),
591 hdc.strControllerType.c_str(),
592 strControllerID.c_str());
593 ++cSCSIused;
594 break;
595 }
596 }
597
598 /* Hard disks */
599 if (vsysThis.mapVirtualDisks.size() > 0)
600 {
601 ovf::VirtualDisksMap::const_iterator itVD;
602 /* Iterate through all hard disks ()*/
603 for (itVD = vsysThis.mapVirtualDisks.begin();
604 itVD != vsysThis.mapVirtualDisks.end();
605 ++itVD)
606 {
607 const ovf::VirtualDisk &hd = itVD->second;
608 /* Get the associated disk image */
609 ovf::DiskImage di;
610 std::map<RTCString, ovf::DiskImage>::iterator foundDisk;
611
612 foundDisk = m->pReader->m_mapDisks.find(hd.strDiskId);
613 if (foundDisk == m->pReader->m_mapDisks.end())
614 continue;
615 else
616 {
617 di = foundDisk->second;
618 }
619
620 /*
621 * Figure out from URI which format the image of disk has.
622 * URI must have inside section <Disk> .
623 * But there aren't strong requirements about correspondence one URI for one disk virtual format.
624 * So possibly, we aren't able to recognize some URIs.
625 */
626
627 ComObjPtr<MediumFormat> mediumFormat;
628 rc = i_findMediumFormatFromDiskImage(di, mediumFormat);
629 if (FAILED(rc))
630 throw rc;
631
632 Bstr bstrFormatName;
633 rc = mediumFormat->COMGETTER(Name)(bstrFormatName.asOutParam());
634 if (FAILED(rc))
635 throw rc;
636 Utf8Str vdf = Utf8Str(bstrFormatName);
637
638 // @todo:
639 // - figure out all possible vmdk formats we also support
640 // - figure out if there is a url specifier for vhd already
641 // - we need a url specifier for the vdi format
642
643 if (vdf.compare("VMDK", Utf8Str::CaseInsensitive) == 0)
644 {
645 /* If the href is empty use the VM name as filename */
646 Utf8Str strFilename = di.strHref;
647 if (!strFilename.length())
648 strFilename = Utf8StrFmt("%s.vmdk", hd.strDiskId.c_str());
649
650 Utf8Str strTargetPath = Utf8Str(strMachineFolder);
651 strTargetPath.append(RTPATH_DELIMITER).append(di.strHref);
652 /*
653 * Remove last extension from the file name if the file is compressed
654 */
655 if (di.strCompression.compare("gzip", Utf8Str::CaseInsensitive)==0)
656 {
657 strTargetPath.stripSuffix();
658 }
659
660 i_searchUniqueDiskImageFilePath(strTargetPath);
661
662 /* find the description for the hard disk controller
663 * that has the same ID as hd.idController */
664 const VirtualSystemDescriptionEntry *pController;
665 if (!(pController = pNewDesc->i_findControllerFromID(hd.idController)))
666 throw setError(E_FAIL,
667 tr("Cannot find hard disk controller with OVF instance ID %RI32 "
668 "to which disk \"%s\" should be attached"),
669 hd.idController,
670 di.strHref.c_str());
671
672 /* controller to attach to, and the bus within that controller */
673 Utf8StrFmt strExtraConfig("controller=%RI16;channel=%RI16",
674 pController->ulIndex,
675 hd.ulAddressOnParent);
676 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskImage,
677 hd.strDiskId,
678 di.strHref,
679 strTargetPath,
680 di.ulSuggestedSizeMB,
681 strExtraConfig);
682 }
683 else if (vdf.compare("RAW", Utf8Str::CaseInsensitive) == 0)
684 {
685 /* If the href is empty use the VM name as filename */
686 Utf8Str strFilename = di.strHref;
687 if (!strFilename.length())
688 strFilename = Utf8StrFmt("%s.iso", hd.strDiskId.c_str());
689
690 Utf8Str strTargetPath = Utf8Str(strMachineFolder)
691 .append(RTPATH_DELIMITER)
692 .append(di.strHref);
693 /*
694 * Remove last extension from the file name if the file is compressed
695 */
696 if (di.strCompression.compare("gzip", Utf8Str::CaseInsensitive)==0)
697 {
698 strTargetPath.stripSuffix();
699 }
700
701 i_searchUniqueDiskImageFilePath(strTargetPath);
702
703 /* find the description for the hard disk controller
704 * that has the same ID as hd.idController */
705 const VirtualSystemDescriptionEntry *pController;
706 if (!(pController = pNewDesc->i_findControllerFromID(hd.idController)))
707 throw setError(E_FAIL,
708 tr("Cannot find disk controller with OVF instance ID %RI32 "
709 "to which disk \"%s\" should be attached"),
710 hd.idController,
711 di.strHref.c_str());
712
713 /* controller to attach to, and the bus within that controller */
714 Utf8StrFmt strExtraConfig("controller=%RI16;channel=%RI16",
715 pController->ulIndex,
716 hd.ulAddressOnParent);
717 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskImage,
718 hd.strDiskId,
719 di.strHref,
720 strTargetPath,
721 di.ulSuggestedSizeMB,
722 strExtraConfig);
723 }
724 else
725 throw setError(VBOX_E_FILE_ERROR,
726 tr("Unsupported format for virtual disk image %s in OVF: \"%s\""),
727 di.strHref.c_str(),
728 di.strFormat.c_str());
729 }
730 }
731
732 m->virtualSystemDescriptions.push_back(pNewDesc);
733 }
734 }
735 catch (HRESULT aRC)
736 {
737 /* On error we clear the list & return */
738 m->virtualSystemDescriptions.clear();
739 rc = aRC;
740 }
741
742 // reset the appliance state
743 alock.acquire();
744 m->state = Data::ApplianceIdle;
745
746 return rc;
747}
748
749/**
750 * Public method implementation. This creates one or more new machines according to the
751 * VirtualSystemScription instances created by Appliance::Interpret().
752 * Thread implementation is in Appliance::i_importImpl().
753 * @param aProgress
754 * @return
755 */
756HRESULT Appliance::importMachines(const std::vector<ImportOptions_T> &aOptions,
757 ComPtr<IProgress> &aProgress)
758{
759 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
760
761 if (aOptions.size())
762 {
763 m->optListImport.setCapacity(aOptions.size());
764 for (size_t i = 0; i < aOptions.size(); ++i)
765 {
766 m->optListImport.insert(i, aOptions[i]);
767 }
768 }
769
770 AssertReturn(!( m->optListImport.contains(ImportOptions_KeepAllMACs)
771 && m->optListImport.contains(ImportOptions_KeepNATMACs) )
772 , E_INVALIDARG);
773
774 // do not allow entering this method if the appliance is busy reading or writing
775 if (!i_isApplianceIdle())
776 return E_ACCESSDENIED;
777
778 if (!m->pReader)
779 return setError(E_FAIL,
780 tr("Cannot import machines without reading it first (call read() before i_importMachines())"));
781
782 ComObjPtr<Progress> progress;
783 HRESULT rc = S_OK;
784 try
785 {
786 rc = i_importImpl(m->locInfo, progress);
787 }
788 catch (HRESULT aRC)
789 {
790 rc = aRC;
791 }
792
793 if (SUCCEEDED(rc))
794 /* Return progress to the caller */
795 progress.queryInterfaceTo(aProgress.asOutParam());
796
797 return rc;
798}
799
800////////////////////////////////////////////////////////////////////////////////
801//
802// Appliance private methods
803//
804////////////////////////////////////////////////////////////////////////////////
805
806/**
807 * Ensures that there is a look-ahead object ready.
808 *
809 * @returns true if there's an object handy, false if end-of-stream.
810 * @throws HRESULT if the next object isn't a regular file. Sets error info
811 * (which is why it's a method on Appliance and not the
812 * ImportStack).
813 */
814bool Appliance::i_importEnsureOvaLookAhead(ImportStack &stack)
815{
816 Assert(stack.hVfsFssOva != NULL);
817 if (stack.hVfsIosOvaLookAhead == NIL_RTVFSIOSTREAM)
818 {
819 RTStrFree(stack.pszOvaLookAheadName);
820 stack.pszOvaLookAheadName = NULL;
821
822 RTVFSOBJTYPE enmType;
823 RTVFSOBJ hVfsObj;
824 int vrc = RTVfsFsStrmNext(stack.hVfsFssOva, &stack.pszOvaLookAheadName, &enmType, &hVfsObj);
825 if (RT_SUCCESS(vrc))
826 {
827 stack.hVfsIosOvaLookAhead = RTVfsObjToIoStream(hVfsObj);
828 RTVfsObjRelease(hVfsObj);
829 if ( ( enmType != RTVFSOBJTYPE_FILE
830 && enmType != RTVFSOBJTYPE_IO_STREAM)
831 || stack.hVfsIosOvaLookAhead == NIL_RTVFSIOSTREAM)
832 throw setError(VBOX_E_FILE_ERROR,
833 tr("Malformed OVA. '%s' is not a regular file (%d)."), stack.pszOvaLookAheadName, enmType);
834 }
835 else if (vrc == VERR_EOF)
836 return false;
837 else
838 throw setErrorVrc(vrc, tr("RTVfsFsStrmNext failed (%Rrc)"), vrc);
839 }
840 return true;
841}
842
843HRESULT Appliance::i_preCheckImageAvailability(ImportStack &stack)
844{
845 if (i_importEnsureOvaLookAhead(stack))
846 return S_OK;
847 throw setError(VBOX_E_FILE_ERROR, tr("Unexpected end of OVA package"));
848 /** @todo r=bird: dunno why this bother returning a value and the caller
849 * having a special 'continue' case for it. It always threw all non-OK
850 * status codes. It's possibly to handle out of order stuff, so that
851 * needs adding to the testcase! */
852}
853
854/**
855 * Setup automatic I/O stream digest calculation, adding it to hOurManifest.
856 *
857 * @returns Passthru I/O stream, of @a hVfsIos if no digest calc needed.
858 * @param hVfsIos The stream to wrap. Always consumed.
859 * @param pszManifestEntry The manifest entry.
860 * @throws Nothing.
861 */
862RTVFSIOSTREAM Appliance::i_importSetupDigestCalculationForGivenIoStream(RTVFSIOSTREAM hVfsIos, const char *pszManifestEntry)
863{
864 int vrc;
865 Assert(!RTManifestPtIosIsInstanceOf(hVfsIos));
866
867 if (m->fDigestTypes == 0)
868 return hVfsIos;
869
870 /* Create the manifest if necessary. */
871 if (m->hOurManifest == NIL_RTMANIFEST)
872 {
873 vrc = RTManifestCreate(0 /*fFlags*/, &m->hOurManifest);
874 AssertRCReturnStmt(vrc, RTVfsIoStrmRelease(hVfsIos), NIL_RTVFSIOSTREAM);
875 }
876
877 /* Setup the stream. */
878 RTVFSIOSTREAM hVfsIosPt;
879 vrc = RTManifestEntryAddPassthruIoStream(m->hOurManifest, hVfsIos, pszManifestEntry, m->fDigestTypes,
880 true /*fReadOrWrite*/, &hVfsIosPt);
881
882 RTVfsIoStrmRelease(hVfsIos); /* always consumed! */
883 if (RT_SUCCESS(vrc))
884 return hVfsIosPt;
885
886 setErrorVrc(vrc, "RTManifestEntryAddPassthruIoStream failed with rc=%Rrc", vrc);
887 return NIL_RTVFSIOSTREAM;
888}
889
890/**
891 * Opens a source file (for reading obviously).
892 *
893 * @param rstrSrcPath The source file to open.
894 * @param pszManifestEntry The manifest entry of the source file. This is
895 * used when constructing our manifest using a pass
896 * thru.
897 * @returns I/O stream handle to the source file.
898 * @throws HRESULT error status, error info set.
899 */
900RTVFSIOSTREAM Appliance::i_importOpenSourceFile(ImportStack &stack, Utf8Str const &rstrSrcPath, const char *pszManifestEntry)
901{
902 /*
903 * Open the source file. Special considerations for OVAs.
904 */
905 RTVFSIOSTREAM hVfsIosSrc;
906 if (stack.hVfsFssOva != NIL_RTVFSFSSTREAM)
907 {
908 for (uint32_t i = 0;; i++)
909 {
910 if (!i_importEnsureOvaLookAhead(stack))
911 throw setErrorBoth(VBOX_E_FILE_ERROR, VERR_EOF,
912 tr("Unexpected end of OVA / internal error - missing '%s' (skipped %u)"),
913 rstrSrcPath.c_str(), i);
914 if (RTStrICmp(stack.pszOvaLookAheadName, rstrSrcPath.c_str()) == 0)
915 break;
916
917 /* release the current object, loop to get the next. */
918 RTVfsIoStrmRelease(stack.claimOvaLookAHead());
919 }
920 hVfsIosSrc = stack.claimOvaLookAHead();
921 }
922 else
923 {
924 int vrc = RTVfsIoStrmOpenNormal(rstrSrcPath.c_str(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE, &hVfsIosSrc);
925 if (RT_FAILURE(vrc))
926 throw setErrorVrc(vrc, tr("Error opening '%s' for reading (%Rrc)"), rstrSrcPath.c_str(), vrc);
927 }
928
929 /*
930 * Digest calculation filtering.
931 */
932 hVfsIosSrc = i_importSetupDigestCalculationForGivenIoStream(hVfsIosSrc, pszManifestEntry);
933 if (hVfsIosSrc == NIL_RTVFSIOSTREAM)
934 throw E_FAIL;
935
936 return hVfsIosSrc;
937}
938
939/**
940 * Creates the destination file and fills it with bytes from the source stream.
941 *
942 * This assumes that we digest the source when fDigestTypes is non-zero, and
943 * thus calls RTManifestPtIosAddEntryNow when done.
944 *
945 * @param rstrDstPath The path to the destination file. Missing path
946 * components will be created.
947 * @param hVfsIosSrc The source I/O stream.
948 * @param rstrSrcLogNm The name of the source for logging and error
949 * messages.
950 * @returns COM status code.
951 * @throws Nothing (as the caller has VFS handles to release).
952 */
953HRESULT Appliance::i_importCreateAndWriteDestinationFile(Utf8Str const &rstrDstPath, RTVFSIOSTREAM hVfsIosSrc,
954 Utf8Str const &rstrSrcLogNm)
955{
956 int vrc;
957
958 /*
959 * Create the output file, including necessary paths.
960 * Any existing file will be overwritten.
961 */
962 HRESULT hrc = VirtualBox::i_ensureFilePathExists(rstrDstPath, true /*fCreate*/);
963 if (SUCCEEDED(hrc))
964 {
965 RTVFSIOSTREAM hVfsIosDst;
966 vrc = RTVfsIoStrmOpenNormal(rstrDstPath.c_str(),
967 RTFILE_O_CREATE_REPLACE | RTFILE_O_WRITE | RTFILE_O_DENY_ALL,
968 &hVfsIosDst);
969 if (RT_SUCCESS(vrc))
970 {
971 /*
972 * Pump the bytes thru. If we fail, delete the output file.
973 */
974 vrc = RTVfsUtilPumpIoStreams(hVfsIosSrc, hVfsIosDst, 0);
975 if (RT_SUCCESS(vrc))
976 hrc = S_OK;
977 else
978 hrc = setErrorVrc(vrc, tr("Error occured decompressing '%s' to '%s' (%Rrc)"),
979 rstrSrcLogNm.c_str(), rstrDstPath.c_str(), vrc);
980 uint32_t cRefs = RTVfsIoStrmRelease(hVfsIosDst);
981 AssertMsg(cRefs == 0, ("cRefs=%u\n", cRefs)); NOREF(cRefs);
982 if (RT_FAILURE(vrc))
983 RTFileDelete(rstrDstPath.c_str());
984 }
985 else
986 hrc = setErrorVrc(vrc, tr("Error opening destionation image '%s' for writing (%Rrc)"), rstrDstPath.c_str(), vrc);
987 }
988 return hrc;
989}
990
991
992/**
993 *
994 * @param pszManifestEntry The manifest entry of the source file. This is
995 * used when constructing our manifest using a pass
996 * thru.
997 * @throws HRESULT error status, error info set.
998 */
999void Appliance::i_importCopyFile(ImportStack &stack, Utf8Str const &rstrSrcPath, Utf8Str const &rstrDstPath,
1000 const char *pszManifestEntry)
1001{
1002 /*
1003 * Just open the file (throws error) and write the destination (nothrow).
1004 */
1005 RTVFSIOSTREAM hVfsIosSrc = i_importOpenSourceFile(stack, rstrSrcPath, pszManifestEntry);
1006 HRESULT hrc = i_importCreateAndWriteDestinationFile(rstrDstPath, hVfsIosSrc, rstrSrcPath);
1007
1008 /*
1009 * Before releasing the source stream, make sure we've successfully added
1010 * the digest to our manifest.
1011 */
1012 if (SUCCEEDED(hrc) && m->fDigestTypes)
1013 {
1014 int vrc = RTManifestPtIosAddEntryNow(hVfsIosSrc);
1015 if (RT_FAILURE(vrc))
1016 hrc = setErrorVrc(vrc, tr("RTManifestPtIosAddEntryNow failed with %Rrc"), vrc);
1017 }
1018
1019 uint32_t cRefs = RTVfsIoStrmRelease(hVfsIosSrc);
1020 AssertMsg(cRefs == 0, ("cRefs=%u\n", cRefs)); NOREF(cRefs);
1021 if (SUCCEEDED(hrc))
1022 return;
1023 throw hrc;
1024}
1025
1026/**
1027 *
1028 * @param pszManifestEntry The manifest entry of the source file. This is
1029 * used when constructing our manifest using a pass
1030 * thru.
1031 * @throws HRESULT error status, error info set.
1032 */
1033void Appliance::i_importDecompressFile(ImportStack &stack, Utf8Str const &rstrSrcPath, Utf8Str const &rstrDstPath,
1034 const char *pszManifestEntry)
1035{
1036 RTVFSIOSTREAM hVfsIosSrcCompressed = i_importOpenSourceFile(stack, rstrSrcPath, pszManifestEntry);
1037
1038 /*
1039 * Add a read ahead thread here. This means reading and digest calculation
1040 * is done on one thread, while unpacking and writing is one on this thread.
1041 */
1042 /** @todo read thread */
1043
1044 /*
1045 * Add decompression step.
1046 */
1047 RTVFSIOSTREAM hVfsIosSrc;
1048 int vrc = RTZipGzipDecompressIoStream(hVfsIosSrcCompressed, 0, &hVfsIosSrc);
1049 if (RT_FAILURE(vrc))
1050 {
1051 RTVfsIoStrmRelease(hVfsIosSrcCompressed);
1052 throw setErrorVrc(vrc, tr("Error initializing gzip decompression for '%s' (%Rrc)"), rstrSrcPath.c_str(), vrc);
1053 }
1054
1055 /*
1056 * Write the stream to the destination file (nothrow).
1057 */
1058 HRESULT hrc = i_importCreateAndWriteDestinationFile(rstrDstPath, hVfsIosSrc, rstrSrcPath);
1059
1060 /*
1061 * Before releasing the source stream, make sure we've successfully added
1062 * the digest to our manifest.
1063 */
1064 if (SUCCEEDED(hrc) && m->fDigestTypes)
1065 {
1066 vrc = RTManifestPtIosAddEntryNow(hVfsIosSrcCompressed);
1067 if (RT_FAILURE(vrc))
1068 hrc = setErrorVrc(vrc, tr("RTManifestPtIosAddEntryNow failed with %Rrc"), vrc);
1069 }
1070
1071 uint32_t cRefs = RTVfsIoStrmRelease(hVfsIosSrc);
1072 AssertMsg(cRefs == 0, ("cRefs=%u\n", cRefs)); NOREF(cRefs);
1073
1074 cRefs = RTVfsIoStrmRelease(hVfsIosSrcCompressed);
1075 AssertMsg(cRefs == 0, ("cRefs=%u\n", cRefs)); NOREF(cRefs);
1076
1077 if (SUCCEEDED(hrc))
1078 return;
1079 throw hrc;
1080}
1081
1082/*******************************************************************************
1083 * Read stuff
1084 ******************************************************************************/
1085
1086/**
1087 * Implementation for reading an OVF (via task).
1088 *
1089 * This starts a new thread which will call
1090 * Appliance::taskThreadImportOrExport() which will then call readFS(). This
1091 * will then open the OVF with ovfreader.cpp.
1092 *
1093 * This is in a separate private method because it is used from two locations:
1094 *
1095 * 1) from the public Appliance::Read().
1096 *
1097 * 2) in a second worker thread; in that case, Appliance::ImportMachines() called Appliance::i_importImpl(), which
1098 * called Appliance::readFSOVA(), which called Appliance::i_importImpl(), which then called this again.
1099 *
1100 * @param aLocInfo The OVF location.
1101 * @param aProgress Where to return the progress object.
1102 * @throws COM error codes will be thrown.
1103 */
1104void Appliance::i_readImpl(const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
1105{
1106 BstrFmt bstrDesc = BstrFmt(tr("Reading appliance '%s'"),
1107 aLocInfo.strPath.c_str());
1108 HRESULT rc;
1109 /* Create the progress object */
1110 aProgress.createObject();
1111 if (aLocInfo.storageType == VFSType_File)
1112 /* 1 operation only */
1113 rc = aProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
1114 bstrDesc.raw(),
1115 TRUE /* aCancelable */);
1116 else
1117 /* 4/5 is downloading, 1/5 is reading */
1118 rc = aProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
1119 bstrDesc.raw(),
1120 TRUE /* aCancelable */,
1121 2, // ULONG cOperations,
1122 5, // ULONG ulTotalOperationsWeight,
1123 BstrFmt(tr("Download appliance '%s'"),
1124 aLocInfo.strPath.c_str()).raw(), // CBSTR bstrFirstOperationDescription,
1125 4); // ULONG ulFirstOperationWeight,
1126 if (FAILED(rc)) throw rc;
1127
1128 /* Initialize our worker task */
1129 TaskOVF *task = NULL;
1130 try
1131 {
1132 task = new TaskOVF(this, TaskOVF::Read, aLocInfo, aProgress);
1133 }
1134 catch (...)
1135 {
1136 throw setError(VBOX_E_OBJECT_NOT_FOUND,
1137 tr("Could not create TaskOVF object for reading the OVF from disk"));
1138 }
1139
1140 rc = task->createThread();
1141 if (FAILED(rc)) throw rc;
1142}
1143
1144/**
1145 * Actual worker code for reading an OVF from disk. This is called from Appliance::taskThreadImportOrExport()
1146 * and therefore runs on the OVF read worker thread. This opens the OVF with ovfreader.cpp.
1147 *
1148 * This runs in one context:
1149 *
1150 * 1) in a first worker thread; in that case, Appliance::Read() called Appliance::readImpl();
1151 *
1152 * @param pTask
1153 * @return
1154 */
1155HRESULT Appliance::i_readFS(TaskOVF *pTask)
1156{
1157 LogFlowFuncEnter();
1158 LogFlowFunc(("Appliance %p\n", this));
1159
1160 AutoCaller autoCaller(this);
1161 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1162
1163 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1164
1165 HRESULT rc;
1166 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
1167 rc = i_readFSOVF(pTask);
1168 else
1169 rc = i_readFSOVA(pTask);
1170
1171 LogFlowFunc(("rc=%Rhrc\n", rc));
1172 LogFlowFuncLeave();
1173
1174 return rc;
1175}
1176
1177HRESULT Appliance::i_readFSOVF(TaskOVF *pTask)
1178{
1179 LogFlowFunc(("'%s'\n", pTask->locInfo.strPath.c_str()));
1180
1181 /*
1182 * Allocate a buffer for filenames and prep it for suffix appending.
1183 */
1184 char *pszNameBuf = (char *)alloca(pTask->locInfo.strPath.length() + 16);
1185 AssertReturn(pszNameBuf, VERR_NO_TMP_MEMORY);
1186 memcpy(pszNameBuf, pTask->locInfo.strPath.c_str(), pTask->locInfo.strPath.length() + 1);
1187 RTPathStripSuffix(pszNameBuf);
1188 size_t const cchBaseName = strlen(pszNameBuf);
1189
1190 /*
1191 * Open the OVF file first since that is what this is all about.
1192 */
1193 RTVFSIOSTREAM hIosOvf;
1194 int vrc = RTVfsIoStrmOpenNormal(pTask->locInfo.strPath.c_str(),
1195 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE, &hIosOvf);
1196 if (RT_FAILURE(vrc))
1197 return setErrorVrc(vrc, tr("Failed to open OVF file '%s' (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
1198
1199 HRESULT hrc = i_readOVFFile(pTask, hIosOvf, RTPathFilename(pTask->locInfo.strPath.c_str())); /* consumes hIosOvf */
1200 if (FAILED(hrc))
1201 return hrc;
1202
1203 /*
1204 * Try open the manifest file (for signature purposes and to determine digest type(s)).
1205 */
1206 RTVFSIOSTREAM hIosMf;
1207 strcpy(&pszNameBuf[cchBaseName], ".mf");
1208 vrc = RTVfsIoStrmOpenNormal(pszNameBuf, RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE, &hIosMf);
1209 if (RT_SUCCESS(vrc))
1210 {
1211 const char * const pszFilenamePart = RTPathFilename(pszNameBuf);
1212 hrc = i_readManifestFile(pTask, hIosMf /*consumed*/, pszFilenamePart);
1213 if (FAILED(hrc))
1214 return hrc;
1215
1216 /*
1217 * Check for the signature file.
1218 */
1219 RTVFSIOSTREAM hIosCert;
1220 strcpy(&pszNameBuf[cchBaseName], ".cert");
1221 vrc = RTVfsIoStrmOpenNormal(pszNameBuf, RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE, &hIosCert);
1222 if (RT_SUCCESS(vrc))
1223 {
1224 hrc = i_readSignatureFile(pTask, hIosCert /*consumed*/, pszFilenamePart);
1225 if (FAILED(hrc))
1226 return hrc;
1227 }
1228 else if (vrc != VERR_FILE_NOT_FOUND && vrc != VERR_PATH_NOT_FOUND)
1229 return setErrorVrc(vrc, tr("Failed to open the signature file '%s' (%Rrc)"), pszNameBuf, vrc);
1230
1231 }
1232 else if (vrc == VERR_FILE_NOT_FOUND || vrc == VERR_PATH_NOT_FOUND)
1233 {
1234 m->fDeterminedDigestTypes = true;
1235 m->fDigestTypes = 0;
1236 }
1237 else
1238 return setErrorVrc(vrc, tr("Failed to open the manifest file '%s' (%Rrc)"), pszNameBuf, vrc);
1239
1240 /*
1241 * Do tail processing (check the signature).
1242 */
1243 hrc = i_readTailProcessing(pTask);
1244
1245 LogFlowFunc(("returns %Rhrc\n", hrc));
1246 return hrc;
1247}
1248
1249HRESULT Appliance::i_readFSOVA(TaskOVF *pTask)
1250{
1251 LogFlowFunc(("'%s'\n", pTask->locInfo.strPath.c_str()));
1252
1253 /*
1254 * Open the tar file as file stream.
1255 */
1256 RTVFSIOSTREAM hVfsIosOva;
1257 int vrc = RTVfsIoStrmOpenNormal(pTask->locInfo.strPath.c_str(),
1258 RTFILE_O_READ | RTFILE_O_DENY_NONE | RTFILE_O_OPEN, &hVfsIosOva);
1259 if (RT_FAILURE(vrc))
1260 return setErrorVrc(vrc, tr("Error opening the OVA file '%s' (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
1261
1262 RTVFSFSSTREAM hVfsFssOva;
1263 vrc = RTZipTarFsStreamFromIoStream(hVfsIosOva, 0 /*fFlags*/, &hVfsFssOva);
1264 RTVfsIoStrmRelease(hVfsIosOva);
1265 if (RT_FAILURE(vrc))
1266 return setErrorVrc(vrc, tr("Error reading the OVA file '%s' (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
1267
1268 /*
1269 * Since jumping thru an OVA file with seekable disk backing is rather
1270 * efficient, we can process .ovf, .mf and .cert files here without any
1271 * strict ordering restrictions.
1272 *
1273 * (Technically, the .ovf-file comes first, while the manifest and its
1274 * optional signature file either follows immediately or at the very end of
1275 * the OVA. The manifest is optional.)
1276 */
1277 char *pszOvfNameBase = NULL;
1278 size_t cchOvfNameBase = 0;
1279 unsigned cLeftToFind = 3;
1280 HRESULT hrc = S_OK;
1281 do
1282 {
1283 char *pszName = NULL;
1284 RTVFSOBJTYPE enmType;
1285 RTVFSOBJ hVfsObj;
1286 vrc = RTVfsFsStrmNext(hVfsFssOva, &pszName, &enmType, &hVfsObj);
1287 if (RT_FAILURE(vrc))
1288 {
1289 if (vrc != VERR_EOF)
1290 hrc = setErrorVrc(vrc, tr("Error reading OVA '%s' (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
1291 break;
1292 }
1293
1294 /* We only care about entries that are files. Get the I/O stream handle for them. */
1295 if ( enmType == RTVFSOBJTYPE_IO_STREAM
1296 || enmType == RTVFSOBJTYPE_FILE)
1297 {
1298 /* Find the suffix and check if this is a possibly interesting file. */
1299 char *pszSuffix = strrchr(pszName, '.');
1300 if ( pszSuffix
1301 && ( RTStrICmp(pszSuffix + 1, "ovf") == 0
1302 || RTStrICmp(pszSuffix + 1, "mf") == 0
1303 || RTStrICmp(pszSuffix + 1, "cert") == 0) )
1304 {
1305 /* Match the OVF base name. */
1306 *pszSuffix = '\0';
1307 if ( pszOvfNameBase == NULL
1308 || RTStrICmp(pszName, pszOvfNameBase) == 0)
1309 {
1310 *pszSuffix = '.';
1311
1312 /* Since we're pretty sure we'll be processing this file, get the I/O stream. */
1313 RTVFSIOSTREAM hVfsIos = RTVfsObjToIoStream(hVfsObj);
1314 Assert(hVfsIos != NIL_RTVFSIOSTREAM);
1315
1316 /* Check for the OVF (should come first). */
1317 if (RTStrICmp(pszSuffix + 1, "ovf") == 0)
1318 {
1319 if (pszOvfNameBase == NULL)
1320 {
1321 hrc = i_readOVFFile(pTask, hVfsIos, pszName);
1322 hVfsIos = NIL_RTVFSIOSTREAM;
1323
1324 /* Set the base name. */
1325 *pszSuffix = '\0';
1326 pszOvfNameBase = pszName;
1327 cchOvfNameBase = strlen(pszName);
1328 pszName = NULL;
1329 cLeftToFind--;
1330 }
1331 else
1332 LogRel(("i_readFSOVA: '%s' contains more than one OVF file ('%s'), picking the first one\n",
1333 pTask->locInfo.strPath.c_str(), pszName));
1334 }
1335 /* Check for manifest. */
1336 else if (RTStrICmp(pszSuffix + 1, "mf") == 0)
1337 {
1338 if (m->hMemFileTheirManifest == NIL_RTVFSFILE)
1339 {
1340 hrc = i_readManifestFile(pTask, hVfsIos, pszName);
1341 hVfsIos = NIL_RTVFSIOSTREAM; /*consumed*/
1342 cLeftToFind--;
1343 }
1344 else
1345 LogRel(("i_readFSOVA: '%s' contains more than one manifest file ('%s'), picking the first one\n",
1346 pTask->locInfo.strPath.c_str(), pszName));
1347 }
1348 /* Check for signature. */
1349 else if (RTStrICmp(pszSuffix + 1, "cert") == 0)
1350 {
1351 if (!m->fSignerCertLoaded)
1352 {
1353 hrc = i_readSignatureFile(pTask, hVfsIos, pszName);
1354 hVfsIos = NIL_RTVFSIOSTREAM; /*consumed*/
1355 cLeftToFind--;
1356 }
1357 else
1358 LogRel(("i_readFSOVA: '%s' contains more than one signature file ('%s'), picking the first one\n",
1359 pTask->locInfo.strPath.c_str(), pszName));
1360 }
1361 else
1362 AssertFailed();
1363 if (hVfsIos != NIL_RTVFSIOSTREAM)
1364 RTVfsIoStrmRelease(hVfsIos);
1365 }
1366 }
1367 }
1368 RTVfsObjRelease(hVfsObj);
1369 RTStrFree(pszName);
1370 } while (cLeftToFind > 0 && SUCCEEDED(hrc));
1371
1372 RTVfsFsStrmRelease(hVfsFssOva);
1373 RTStrFree(pszOvfNameBase);
1374
1375 /*
1376 * Check that we found and OVF file.
1377 */
1378 if (SUCCEEDED(hrc) && !pszOvfNameBase)
1379 hrc = setError(VBOX_E_FILE_ERROR, tr("OVA '%s' does not contain an .ovf-file"), pTask->locInfo.strPath.c_str());
1380 if (SUCCEEDED(hrc))
1381 {
1382 /*
1383 * Do tail processing (check the signature).
1384 */
1385 hrc = i_readTailProcessing(pTask);
1386 }
1387 LogFlowFunc(("returns %Rhrc\n", hrc));
1388 return hrc;
1389}
1390
1391/**
1392 * Reads & parses the OVF file.
1393 *
1394 * @param pTask The read task.
1395 * @param hVfsIosOvf The I/O stream for the OVF. The reference is
1396 * always consumed.
1397 * @param pszManifestEntry The manifest entry name.
1398 * @returns COM status code, error info set.
1399 * @throws Nothing
1400 */
1401HRESULT Appliance::i_readOVFFile(TaskOVF *pTask, RTVFSIOSTREAM hVfsIosOvf, const char *pszManifestEntry)
1402{
1403 LogFlowFunc(("%s[%s]\n", pTask->locInfo.strPath.c_str(), pszManifestEntry));
1404
1405 /*
1406 * Set the OVF manifest entry name (needed for tweaking the manifest
1407 * validation during import).
1408 */
1409 try { m->strOvfManifestEntry = pszManifestEntry; }
1410 catch (...) { return E_OUTOFMEMORY; }
1411
1412 /*
1413 * Set up digest calculation.
1414 */
1415 hVfsIosOvf = i_importSetupDigestCalculationForGivenIoStream(hVfsIosOvf, pszManifestEntry);
1416 if (hVfsIosOvf == NIL_RTVFSIOSTREAM)
1417 return VBOX_E_FILE_ERROR;
1418
1419 /*
1420 * Read the OVF into a memory buffer and parse it.
1421 */
1422 void *pvBufferedOvf;
1423 size_t cbBufferedOvf;
1424 int vrc = RTVfsIoStrmReadAll(hVfsIosOvf, &pvBufferedOvf, &cbBufferedOvf);
1425 uint32_t cRefs = RTVfsIoStrmRelease(hVfsIosOvf); /* consumes stream handle. */
1426 Assert(cRefs == 0);
1427 if (RT_FAILURE(vrc))
1428 return setErrorVrc(vrc, tr("Could not read the OVF file for '%s' (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
1429
1430 HRESULT hrc;
1431 try
1432 {
1433 m->pReader = new ovf::OVFReader(pvBufferedOvf, cbBufferedOvf, pTask->locInfo.strPath);
1434 hrc = S_OK;
1435 }
1436 catch (RTCError &rXcpt) // includes all XML exceptions
1437 {
1438 hrc = setError(VBOX_E_FILE_ERROR, rXcpt.what());
1439 }
1440 catch (HRESULT aRC)
1441 {
1442 hrc = aRC;
1443 }
1444 catch (...)
1445 {
1446 hrc = E_FAIL;
1447 }
1448 LogFlowFunc(("OVFReader(%s) -> rc=%Rhrc\n", pTask->locInfo.strPath.c_str(), hrc));
1449
1450 RTVfsIoStrmReadAllFree(pvBufferedOvf, cbBufferedOvf);
1451 if (SUCCEEDED(hrc))
1452 {
1453 /*
1454 * If we see an OVF v2.0 envelope, select only the SHA-256 digest.
1455 */
1456 if ( !m->fDeterminedDigestTypes
1457 && m->pReader->m_envelopeData.getOVFVersion() == ovf::OVFVersion_2_0)
1458 m->fDigestTypes &= ~RTMANIFEST_ATTR_SHA256;
1459 }
1460
1461 return hrc;
1462}
1463
1464/**
1465 * Reads & parses the manifest file.
1466 *
1467 * @param pTask The read task.
1468 * @param hVfsIosMf The I/O stream for the manifest file. The
1469 * reference is always consumed.
1470 * @param pszSubFileNm The manifest filename (no path) for error
1471 * messages and logging.
1472 * @returns COM status code, error info set.
1473 * @throws Nothing
1474 */
1475HRESULT Appliance::i_readManifestFile(TaskOVF *pTask, RTVFSIOSTREAM hVfsIosMf, const char *pszSubFileNm)
1476{
1477 LogFlowFunc(("%s[%s]\n", pTask->locInfo.strPath.c_str(), pszSubFileNm));
1478
1479 /*
1480 * Copy the manifest into a memory backed file so we can later do signature
1481 * validation indepentend of the algorithms used by the signature.
1482 */
1483 int vrc = RTVfsMemorizeIoStreamAsFile(hVfsIosMf, RTFILE_O_READ, &m->hMemFileTheirManifest);
1484 RTVfsIoStrmRelease(hVfsIosMf); /* consumes stream handle. */
1485 if (RT_FAILURE(vrc))
1486 return setErrorVrc(vrc, tr("Error reading the manifest file '%s' for '%s' (%Rrc)"),
1487 pszSubFileNm, pTask->locInfo.strPath.c_str(), vrc);
1488
1489 /*
1490 * Parse the manifest.
1491 */
1492 Assert(m->hTheirManifest == NIL_RTMANIFEST);
1493 vrc = RTManifestCreate(0 /*fFlags*/, &m->hTheirManifest);
1494 AssertStmt(RT_SUCCESS(vrc), Global::vboxStatusCodeToCOM(vrc));
1495
1496 char szErr[256];
1497 RTVFSIOSTREAM hVfsIos = RTVfsFileToIoStream(m->hMemFileTheirManifest);
1498 vrc = RTManifestReadStandardEx(m->hTheirManifest, hVfsIos, szErr, sizeof(szErr));
1499 RTVfsIoStrmRelease(hVfsIos);
1500 if (RT_FAILURE(vrc))
1501 throw setErrorVrc(vrc, tr("Failed to parse manifest file '%s' for '%s' (%Rrc): %s"),
1502 pszSubFileNm, pTask->locInfo.strPath.c_str(), vrc, szErr);
1503
1504 /*
1505 * Check which digest files are used.
1506 * Note! the file could be empty, in which case fDigestTypes is set to 0.
1507 */
1508 vrc = RTManifestQueryAllAttrTypes(m->hTheirManifest, true /*fEntriesOnly*/, &m->fDigestTypes);
1509 AssertRCReturn(vrc, Global::vboxStatusCodeToCOM(vrc));
1510 m->fDeterminedDigestTypes = true;
1511
1512 m->fSha256 = RT_BOOL(m->fDigestTypes & RTMANIFEST_ATTR_SHA256); /** @todo retire this member */
1513 return S_OK;
1514}
1515
1516/**
1517 * Reads the signature & certificate file.
1518 *
1519 * @param pTask The read task.
1520 * @param hVfsIosCert The I/O stream for the signature file. The
1521 * reference is always consumed.
1522 * @param pszSubFileNm The signature filename (no path) for error
1523 * messages and logging. Used to construct
1524 * .mf-file name.
1525 * @returns COM status code, error info set.
1526 * @throws Nothing
1527 */
1528HRESULT Appliance::i_readSignatureFile(TaskOVF *pTask, RTVFSIOSTREAM hVfsIosCert, const char *pszSubFileNm)
1529{
1530 LogFlowFunc(("%s[%s]\n", pTask->locInfo.strPath.c_str(), pszSubFileNm));
1531
1532 /*
1533 * Construct the manifest filename from pszSubFileNm.
1534 */
1535 Utf8Str strManifestName;
1536 try
1537 {
1538 const char *pszSuffix = strrchr(pszSubFileNm, '.');
1539 AssertReturn(pszSuffix, E_FAIL);
1540 strManifestName = Utf8Str(pszSubFileNm, pszSuffix - pszSubFileNm);
1541 strManifestName.append(".mf");
1542 }
1543 catch (...)
1544 {
1545 return E_OUTOFMEMORY;
1546 }
1547
1548 /*
1549 * Copy the manifest into a memory buffer. We'll do the signature processing
1550 * later to not force any specific order in the OVAs or any other archive we
1551 * may be accessing later.
1552 */
1553 void *pvSignature;
1554 size_t cbSignature;
1555 int vrc = RTVfsIoStrmReadAll(hVfsIosCert, &pvSignature, &cbSignature);
1556 RTVfsIoStrmRelease(hVfsIosCert); /* consumes stream handle. */
1557 if (RT_FAILURE(vrc))
1558 return setErrorVrc(vrc, tr("Error reading the signature file '%s' for '%s' (%Rrc)"),
1559 pszSubFileNm, pTask->locInfo.strPath.c_str(), vrc);
1560
1561 /*
1562 * Parse the signing certificate. Unlike the manifest parser we use below,
1563 * this API ignores parse of the file that aren't relevant.
1564 */
1565 RTERRINFOSTATIC StaticErrInfo;
1566 vrc = RTCrX509Certificate_ReadFromBuffer(&m->SignerCert, pvSignature, cbSignature, 0 /*fFlags*/,
1567 &g_RTAsn1DefaultAllocator, RTErrInfoInitStatic(&StaticErrInfo), pszSubFileNm);
1568 HRESULT hrc;
1569 if (RT_SUCCESS(vrc))
1570 {
1571 m->fSignerCertLoaded = true;
1572
1573 /*
1574 * Find the start of the certificate part of the file, so we can avoid
1575 * upsetting the manifest parser with it.
1576 */
1577 char *pszSplit = (char *)RTCrPemFindFirstSectionInContent(pvSignature, cbSignature,
1578 g_aRTCrX509CertificateMarkers, g_cRTCrX509CertificateMarkers);
1579 if (pszSplit)
1580 while ( pszSplit != (char *)pvSignature
1581 && pszSplit[-1] != '\n'
1582 && pszSplit[-1] != '\r')
1583 pszSplit--;
1584 else
1585 {
1586 AssertLogRelMsgFailed(("Failed to find BEGIN CERTIFICATE markers in '%s'::'%s' - impossible unless it's a DER encoded certificate!",
1587 pTask->locInfo.strPath.c_str(), pszSubFileNm));
1588 pszSplit = (char *)pvSignature + cbSignature;
1589 }
1590 *pszSplit = '\0';
1591
1592 /*
1593 * Now, read the manifest part. We use the IPRT manifest reader here
1594 * to avoid duplicating code and be somewhat flexible wrt the digest
1595 * type choosen by the signer.
1596 */
1597 RTMANIFEST hSignedDigestManifest;
1598 vrc = RTManifestCreate(0 /*fFlags*/, &hSignedDigestManifest);
1599 if (RT_SUCCESS(vrc))
1600 {
1601 RTVFSIOSTREAM hVfsIosTmp;
1602 vrc = RTVfsIoStrmFromBuffer(RTFILE_O_READ, pvSignature, pszSplit - (char *)pvSignature, &hVfsIosTmp);
1603 if (RT_SUCCESS(vrc))
1604 {
1605 vrc = RTManifestReadStandardEx(hSignedDigestManifest, hVfsIosTmp, StaticErrInfo.szMsg, sizeof(StaticErrInfo.szMsg));
1606 RTVfsIoStrmRelease(hVfsIosTmp);
1607 if (RT_SUCCESS(vrc))
1608 {
1609 /*
1610 * Get signed digest, we prefer SHA-2, so explicitly query those first.
1611 */
1612 uint32_t fDigestType;
1613 char szSignedDigest[_8K + 1];
1614 vrc = RTManifestEntryQueryAttr(hSignedDigestManifest, strManifestName.c_str(), NULL,
1615 RTMANIFEST_ATTR_SHA512 | RTMANIFEST_ATTR_SHA256,
1616 szSignedDigest, sizeof(szSignedDigest), &fDigestType);
1617 if (vrc == VERR_MANIFEST_ATTR_TYPE_NOT_FOUND)
1618 vrc = RTManifestEntryQueryAttr(hSignedDigestManifest, strManifestName.c_str(), NULL,
1619 RTMANIFEST_ATTR_ANY, szSignedDigest, sizeof(szSignedDigest), &fDigestType);
1620 if (RT_SUCCESS(vrc))
1621 {
1622 const char *pszSignedDigest = RTStrStrip(szSignedDigest);
1623 size_t cbSignedDigest = strlen(pszSignedDigest) / 2;
1624 uint8_t abSignedDigest[sizeof(szSignedDigest) / 2];
1625 vrc = RTStrConvertHexBytes(szSignedDigest, abSignedDigest, cbSignedDigest, 0 /*fFlags*/);
1626 if (RT_SUCCESS(vrc))
1627 {
1628 /*
1629 * Convert it to RTDIGESTTYPE_XXX and save the binary value for later use.
1630 */
1631 switch (fDigestType)
1632 {
1633 case RTMANIFEST_ATTR_SHA1: m->enmSignedDigestType = RTDIGESTTYPE_SHA1; break;
1634 case RTMANIFEST_ATTR_SHA256: m->enmSignedDigestType = RTDIGESTTYPE_SHA256; break;
1635 case RTMANIFEST_ATTR_SHA512: m->enmSignedDigestType = RTDIGESTTYPE_SHA512; break;
1636 case RTMANIFEST_ATTR_MD5: m->enmSignedDigestType = RTDIGESTTYPE_MD5; break;
1637 default: AssertFailed(); m->enmSignedDigestType = RTDIGESTTYPE_INVALID; break;
1638 }
1639 if (m->enmSignedDigestType != RTDIGESTTYPE_INVALID)
1640 {
1641 m->pbSignedDigest = (uint8_t *)RTMemDup(abSignedDigest, cbSignedDigest);
1642 m->cbSignedDigest = cbSignedDigest;
1643 hrc = S_OK;
1644 }
1645 else
1646 hrc = setError(E_FAIL, tr("Unsupported signed digest type (%#x)"), fDigestType);
1647 }
1648 else
1649 hrc = setErrorVrc(vrc, tr("Error reading signed manifest digest: %Rrc"), vrc);
1650 }
1651 else if (vrc == VERR_NOT_FOUND)
1652 hrc = setErrorVrc(vrc, tr("Could not locate signed digest for '%s' in the cert-file for '%s'"),
1653 strManifestName.c_str(), pTask->locInfo.strPath.c_str());
1654 else
1655 hrc = setErrorVrc(vrc, tr("RTManifestEntryQueryAttr failed unexpectedly: %Rrc"), vrc);
1656 }
1657 else
1658 hrc = setErrorVrc(vrc, tr("Error parsing the .cert-file for '%s': %s"),
1659 pTask->locInfo.strPath.c_str(), StaticErrInfo.szMsg);
1660 }
1661 else
1662 hrc = E_OUTOFMEMORY;
1663 RTManifestRelease(hSignedDigestManifest);
1664 }
1665 else
1666 hrc = E_OUTOFMEMORY;
1667 }
1668 else
1669 hrc = setErrorVrc(vrc, tr("Error reading the signer's certificate from '%s' for '%s' (%Rrc): %s"),
1670 pszSubFileNm, pTask->locInfo.strPath.c_str(), vrc, StaticErrInfo.Core.pszMsg);
1671
1672 RTVfsIoStrmReadAllFree(pvSignature, cbSignature);
1673 LogFlowFunc(("returns %Rhrc (%Rrc)\n", hrc, vrc));
1674 return hrc;
1675}
1676
1677
1678/**
1679 * Does tail processing after the files have been read in.
1680 *
1681 * @param pTask The read task.
1682 * @returns COM status.
1683 * @throws Nothing!
1684 */
1685HRESULT Appliance::i_readTailProcessing(TaskOVF *pTask)
1686{
1687 /*
1688 * Parse and validate the signature file.
1689 *
1690 * The signature file has two parts, manifest part and a PEM encoded
1691 * certificate. The former contains an entry for the manifest file with a
1692 * digest that is encrypted with the certificate in the latter part.
1693 */
1694 if (m->pbSignedDigest)
1695 {
1696 /* Since we're validating the digest of the manifest, there have to be
1697 a manifest. We cannot allow a the manifest to be missing. */
1698 if (m->hMemFileTheirManifest == NIL_RTVFSFILE)
1699 return setError(VBOX_E_FILE_ERROR, tr("Found .cert-file but no .mf-file for '%s'"), pTask->locInfo.strPath.c_str());
1700
1701 /*
1702 * Validate the signed digest.
1703 */
1704 HRESULT hrc;
1705
1706 /* Calc the digest of the manifest using the algorithm found above. */
1707 RTCRDIGEST hDigest;
1708 int vrc = RTCrDigestCreateByType(&hDigest, m->enmSignedDigestType);
1709 if (RT_SUCCESS(vrc))
1710 {
1711 vrc = RTCrDigestUpdateFromVfsFile(hDigest, m->hMemFileTheirManifest, true /*fRewindFile*/);
1712 if (RT_SUCCESS(vrc))
1713 {
1714 /** @todo convert to something like RTCrPkixPubKeyVerifySignature! */
1715 /* Verify the signature using the certificate. */
1716 RTCRPKIXSIGNATURE hSignature;
1717 vrc = RTCrPkixSignatureCreateByObjId(&hSignature,
1718 &m->SignerCert.TbsCertificate.SubjectPublicKeyInfo.Algorithm.Algorithm,
1719 false /*fSigning*/,
1720 &m->SignerCert.TbsCertificate.SubjectPublicKeyInfo.SubjectPublicKey,
1721 NULL);
1722 if (RT_SUCCESS(vrc))
1723 {
1724 vrc = RTCrPkixSignatureVerify(hSignature, hDigest, m->pbSignedDigest, m->cbSignedDigest);
1725 if (RT_SUCCESS(vrc))
1726 {
1727 m->fSignatureValid = true;
1728 hrc = S_OK;
1729 }
1730 else if (vrc == VERR_CR_PKIX_SIGNATURE_MISMATCH)
1731 hrc = setErrorVrc(vrc, tr("The manifest signature does not match"));
1732 else
1733 hrc = setErrorVrc(vrc, tr("Error validating the manifest signature (%Rrc)"), vrc);
1734 RTCrPkixSignatureRelease(hSignature);
1735 }
1736 }
1737 RTCrDigestRelease(hDigest);
1738 }
1739 else
1740 hrc = setErrorVrc(vrc, tr("RTCrDigestCreateByType failed: %Rrc"), vrc);
1741
1742 /*
1743 * If the signed digest checked out, validate the certificate.
1744 */
1745 if (SUCCEEDED(hrc))
1746 {
1747 RTERRINFOSTATIC StaticErrInfo;
1748 if (RTCrX509Certificate_IsSelfSigned(&m->SignerCert))
1749 {
1750 /*
1751 * It's a self signed certificate. We assume the frontend will
1752 * present this fact to the user and give a choice whether this
1753 * is acceptible. But, first make sure it makes internal sense.
1754 */
1755 /** @todo Not entirely sure if we care whether a self issued certificate is
1756 marked as CA. But let's be a little bit picky about it for now. */
1757 if ( m->SignerCert.TbsCertificate.T3.pBasicConstraints
1758 && m->SignerCert.TbsCertificate.T3.pBasicConstraints->CA.fValue)
1759 {
1760 vrc = RTCrX509Certificate_VerifySignatureSelfSigned(&m->SignerCert, RTErrInfoInitStatic(&StaticErrInfo));
1761 if (RT_SUCCESS(vrc))
1762 {
1763 /** @todo Consider the certificate expiration date!! Though see timestamp
1764 * concern below in the non-self-issued case */
1765 hrc = S_OK;
1766 m->fCertificateValid = true;
1767 }
1768 else
1769 hrc = setErrorVrc(vrc, tr("Verification of the self signed certificate used to sign '%s' failed (%Rrc): %s"),
1770 pTask->locInfo.strPath.c_str(), vrc, StaticErrInfo.Core.pszMsg);
1771 }
1772 else
1773 hrc = setError(E_FAIL,
1774 tr("Self signed certificate used to sign '%s' is not marked as certificate authority (CA)"),
1775 pTask->locInfo.strPath.c_str());
1776 }
1777 else
1778 {
1779 /*
1780 * The certificate is not self-signed. Use the system certificate
1781 * stores to try validate it.
1782 */
1783 RTCRX509CERTPATHS hCertPaths;
1784 vrc = RTCrX509CertPathsCreate(&hCertPaths, &m->SignerCert);
1785 if (RT_SUCCESS(vrc))
1786 {
1787 /* Get trusted certificates from the system and add them to the path finding mission. */
1788 RTCRSTORE hTrustedCerts;
1789 vrc = RTCrStoreCreateSnapshotOfUserAndSystemTrustedCAsAndCerts(&hTrustedCerts,
1790 RTErrInfoInitStatic(&StaticErrInfo));
1791 if (RT_SUCCESS(vrc))
1792 {
1793 vrc = RTCrX509CertPathsSetTrustedStore(hCertPaths, hTrustedCerts);
1794 if (RT_FAILURE(vrc))
1795 hrc = setError(E_FAIL, tr("RTCrX509CertPathsSetTrustedStore failed (%Rrc)"), vrc);
1796 RTCrStoreRelease(hTrustedCerts);
1797 }
1798 else
1799 hrc = setError(E_FAIL,
1800 tr("Failed to query trusted CAs and Certificates from the system and for the current user (%Rrc, %s)"),
1801 vrc, StaticErrInfo.Core.pszMsg);
1802
1803 /* Add untrusted intermediate certificates. */
1804 if (RT_SUCCESS(vrc))
1805 {
1806 /// @todo RTCrX509CertPathsSetUntrustedStore(hCertPaths, hAdditionalCerts);
1807 /// By scanning for additional certificates in the .cert file? It would be
1808 /// convenient to be able to supply intermediate certificates for the user,
1809 /// right? Or would that be unacceptable as it may weaken security?
1810 ///
1811 /// Anyway, we should look for intermediate certificates on the system, at
1812 /// least.
1813 }
1814
1815 /* Set the validation timestamp? */
1816 if (RT_SUCCESS(vrc))
1817 {
1818 /// @todo RTCrX509CertPathsSetValidTimeSpec(hCertPaths, pValidationTime);
1819 /// Not having a timestamp signature is a bit crippling to deployment using
1820 /// certificates with a short expiration date... Need to allow the user to
1821 }
1822
1823 if (RT_SUCCESS(vrc))
1824 {
1825 /*
1826 * Do the building and verification.
1827 */
1828 vrc = RTCrX509CertPathsBuild(hCertPaths, RTErrInfoInitStatic(&StaticErrInfo));
1829 if (RT_SUCCESS(vrc))
1830 {
1831 vrc = RTCrX509CertPathsValidateAll(hCertPaths, NULL, RTErrInfoInitStatic(&StaticErrInfo));
1832 if (RT_SUCCESS(vrc))
1833 {
1834 /*
1835 * The certificate is good.
1836 */
1837 /** @todo check the certificate purpose? */
1838 m->fCertificateValid = true;
1839 hrc = S_OK;
1840 }
1841 else
1842 hrc = setError(E_FAIL, tr("Certificate path validation failed (%Rrc, %s)"),
1843 vrc, StaticErrInfo.Core.pszMsg);
1844 }
1845 else
1846 hrc = setError(E_FAIL, tr("Certificate path building failed (%Rrc, %s)"),
1847 vrc, StaticErrInfo.Core.pszMsg);
1848
1849 }
1850 RTCrX509CertPathsRelease(hCertPaths);
1851 }
1852 }
1853 }
1854 }
1855
1856 /** @todo provide details about the signatory, signature, etc. */
1857
1858 /*
1859 * If there is a manifest, check that the OVF digest matches up (if present).
1860 */
1861
1862 NOREF(pTask);
1863 return S_OK;
1864}
1865
1866
1867
1868/*******************************************************************************
1869 * Import stuff
1870 ******************************************************************************/
1871
1872/**
1873 * Implementation for importing OVF data into VirtualBox. This starts a new thread which will call
1874 * Appliance::taskThreadImportOrExport().
1875 *
1876 * This creates one or more new machines according to the VirtualSystemScription instances created by
1877 * Appliance::Interpret().
1878 *
1879 * This is in a separate private method because it is used from one location:
1880 *
1881 * 1) from the public Appliance::ImportMachines().
1882 *
1883 * @param aLocInfo
1884 * @param aProgress
1885 * @return
1886 */
1887HRESULT Appliance::i_importImpl(const LocationInfo &locInfo,
1888 ComObjPtr<Progress> &progress)
1889{
1890 HRESULT rc = S_OK;
1891
1892 SetUpProgressMode mode;
1893 if (locInfo.storageType == VFSType_File)
1894 mode = ImportFile;
1895 else
1896 mode = ImportS3;
1897
1898 rc = i_setUpProgress(progress,
1899 BstrFmt(tr("Importing appliance '%s'"), locInfo.strPath.c_str()),
1900 mode);
1901 if (FAILED(rc)) throw rc;
1902
1903 /* Initialize our worker task */
1904 TaskOVF* task = NULL;
1905 try
1906 {
1907 task = new TaskOVF(this, TaskOVF::Import, locInfo, progress);
1908 }
1909 catch(...)
1910 {
1911 delete task;
1912 throw rc = setError(VBOX_E_OBJECT_NOT_FOUND,
1913 tr("Could not create TaskOVF object for importing OVF data into VirtualBox"));
1914 }
1915
1916 rc = task->createThread();
1917 if (FAILED(rc)) throw rc;
1918
1919 return rc;
1920}
1921
1922/**
1923 * Actual worker code for importing OVF data into VirtualBox.
1924 *
1925 * This is called from Appliance::taskThreadImportOrExport() and therefore runs
1926 * on the OVF import worker thread. This creates one or more new machines
1927 * according to the VirtualSystemScription instances created by
1928 * Appliance::Interpret().
1929 *
1930 * This runs in two contexts:
1931 *
1932 * 1) in a first worker thread; in that case, Appliance::ImportMachines() called
1933 * Appliance::i_importImpl();
1934 *
1935 * 2) in a second worker thread; in that case, Appliance::ImportMachines()
1936 * called Appliance::i_importImpl(), which called Appliance::i_importFSOVA(),
1937 * which called Appliance::i_importImpl(), which then called this again.
1938 *
1939 * @param pTask The OVF task data.
1940 * @return COM status code.
1941 */
1942HRESULT Appliance::i_importFS(TaskOVF *pTask)
1943{
1944 LogFlowFuncEnter();
1945 LogFlowFunc(("Appliance %p\n", this));
1946
1947 /* Change the appliance state so we can safely leave the lock while doing
1948 * time-consuming disk imports; also the below method calls do all kinds of
1949 * locking which conflicts with the appliance object lock. */
1950 AutoWriteLock writeLock(this COMMA_LOCKVAL_SRC_POS);
1951 /* Check if the appliance is currently busy. */
1952 if (!i_isApplianceIdle())
1953 return E_ACCESSDENIED;
1954 /* Set the internal state to importing. */
1955 m->state = Data::ApplianceImporting;
1956
1957 HRESULT rc = S_OK;
1958
1959 /* Clear the list of imported machines, if any */
1960 m->llGuidsMachinesCreated.clear();
1961
1962 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
1963 rc = i_importFSOVF(pTask, writeLock);
1964 else
1965 rc = i_importFSOVA(pTask, writeLock);
1966 if (FAILED(rc))
1967 {
1968 /* With _whatever_ error we've had, do a complete roll-back of
1969 * machines and disks we've created */
1970 writeLock.release();
1971 ErrorInfoKeeper eik;
1972 for (list<Guid>::iterator itID = m->llGuidsMachinesCreated.begin();
1973 itID != m->llGuidsMachinesCreated.end();
1974 ++itID)
1975 {
1976 Guid guid = *itID;
1977 Bstr bstrGuid = guid.toUtf16();
1978 ComPtr<IMachine> failedMachine;
1979 HRESULT rc2 = mVirtualBox->FindMachine(bstrGuid.raw(), failedMachine.asOutParam());
1980 if (SUCCEEDED(rc2))
1981 {
1982 SafeIfaceArray<IMedium> aMedia;
1983 rc2 = failedMachine->Unregister(CleanupMode_DetachAllReturnHardDisksOnly, ComSafeArrayAsOutParam(aMedia));
1984 ComPtr<IProgress> pProgress2;
1985 rc2 = failedMachine->DeleteConfig(ComSafeArrayAsInParam(aMedia), pProgress2.asOutParam());
1986 pProgress2->WaitForCompletion(-1);
1987 }
1988 }
1989 writeLock.acquire();
1990 }
1991
1992 /* Reset the state so others can call methods again */
1993 m->state = Data::ApplianceIdle;
1994
1995 LogFlowFunc(("rc=%Rhrc\n", rc));
1996 LogFlowFuncLeave();
1997 return rc;
1998}
1999
2000HRESULT Appliance::i_importFSOVF(TaskOVF *pTask, AutoWriteLockBase &rWriteLock)
2001{
2002 return i_importDoIt(pTask, rWriteLock);
2003}
2004
2005HRESULT Appliance::i_importFSOVA(TaskOVF *pTask, AutoWriteLockBase &rWriteLock)
2006{
2007 LogFlowFuncEnter();
2008
2009 /*
2010 * Open the tar file as file stream.
2011 */
2012 RTVFSIOSTREAM hVfsIosOva;
2013 int vrc = RTVfsIoStrmOpenNormal(pTask->locInfo.strPath.c_str(),
2014 RTFILE_O_READ | RTFILE_O_DENY_NONE | RTFILE_O_OPEN, &hVfsIosOva);
2015 if (RT_FAILURE(vrc))
2016 return setErrorVrc(vrc, tr("Error opening the OVA file '%s' (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
2017
2018 RTVFSFSSTREAM hVfsFssOva;
2019 vrc = RTZipTarFsStreamFromIoStream(hVfsIosOva, 0 /*fFlags*/, &hVfsFssOva);
2020 RTVfsIoStrmRelease(hVfsIosOva);
2021 if (RT_FAILURE(vrc))
2022 return setErrorVrc(vrc, tr("Error reading the OVA file '%s' (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
2023
2024 /*
2025 * Join paths with the i_importFSOVF code.
2026 *
2027 * Note! We don't need to skip the OVF, manifest or signature files, as the
2028 * i_importMachineGeneric, i_importVBoxMachine and i_importOpenSourceFile
2029 * code will deal with this (as there could be other files in the OVA
2030 * that we don't process, like 'de-DE-resources.xml' in EXAMPLE 1,
2031 * Appendix D.1, OVF v2.1.0).
2032 */
2033 HRESULT hrc = i_importDoIt(pTask, rWriteLock, hVfsFssOva);
2034
2035 RTVfsFsStrmRelease(hVfsFssOva);
2036
2037 LogFlowFunc(("returns %Rhrc\n", hrc));
2038 return hrc;
2039}
2040
2041/**
2042 * Does the actual importing after the caller has made the source accessible.
2043 *
2044 * @param pTask The import task.
2045 * @param rWriteLock The write lock the caller's caller is holding,
2046 * will be released for some reason.
2047 * @param hVfsFssOva The file system stream if OVA, NIL if not.
2048 * @returns COM status code.
2049 * @throws Nothing.
2050 */
2051HRESULT Appliance::i_importDoIt(TaskOVF *pTask, AutoWriteLockBase &rWriteLock, RTVFSFSSTREAM hVfsFssOva /*= NIL_RTVFSFSSTREAM*/)
2052{
2053 rWriteLock.release();
2054
2055 HRESULT hrc = E_FAIL;
2056 try
2057 {
2058 /*
2059 * Create the import stack for the rollback on errors.
2060 */
2061 ImportStack stack(pTask->locInfo, m->pReader->m_mapDisks, pTask->pProgress, hVfsFssOva);
2062
2063 try
2064 {
2065 /* Do the importing. */
2066 i_importMachines(stack);
2067
2068 /* We should've processed all the files now, so compare. */
2069 hrc = i_verifyManifestFile(stack);
2070 }
2071 catch (HRESULT hrcXcpt)
2072 {
2073 hrc = hrcXcpt;
2074 }
2075 catch (...)
2076 {
2077 AssertFailed();
2078 hrc = E_FAIL;
2079 }
2080 if (FAILED(hrc))
2081 {
2082 /*
2083 * Restoring original UUID from OVF description file.
2084 * During import VBox creates new UUIDs for imported images and
2085 * assigns them to the images. In case of failure we have to restore
2086 * the original UUIDs because those new UUIDs are obsolete now and
2087 * won't be used anymore.
2088 */
2089 ErrorInfoKeeper eik; /* paranoia */
2090 list< ComObjPtr<VirtualSystemDescription> >::const_iterator itvsd;
2091 /* Iterate through all virtual systems of that appliance */
2092 for (itvsd = m->virtualSystemDescriptions.begin();
2093 itvsd != m->virtualSystemDescriptions.end();
2094 ++itvsd)
2095 {
2096 ComObjPtr<VirtualSystemDescription> vsdescThis = (*itvsd);
2097 settings::MachineConfigFile *pConfig = vsdescThis->m->pConfig;
2098 if(vsdescThis->m->pConfig!=NULL)
2099 stack.restoreOriginalUUIDOfAttachedDevice(pConfig);
2100 }
2101 }
2102 }
2103 catch (...)
2104 {
2105 hrc = E_FAIL;
2106 AssertFailed();
2107 }
2108
2109 rWriteLock.acquire();
2110 return hrc;
2111}
2112
2113/**
2114 * Undocumented, you figure it from the name.
2115 *
2116 * @returns Undocumented
2117 * @param stack Undocumented.
2118 */
2119HRESULT Appliance::i_verifyManifestFile(ImportStack &stack)
2120{
2121 LogFlowThisFuncEnter();
2122 HRESULT hrc;
2123 int vrc;
2124
2125 /*
2126 * No manifest is fine, it always matches.
2127 */
2128 if (m->hTheirManifest == NIL_RTMANIFEST)
2129 hrc = S_OK;
2130 else
2131 {
2132 /*
2133 * Hack: If the manifest we just read doesn't have a digest for the OVF, copy
2134 * it from the manifest we got from the caller.
2135 * @bugref{6022#c119}
2136 */
2137 if ( !RTManifestEntryExists(m->hTheirManifest, m->strOvfManifestEntry.c_str())
2138 && RTManifestEntryExists(m->hOurManifest, m->strOvfManifestEntry.c_str()) )
2139 {
2140 uint32_t fType = 0;
2141 char szDigest[512 + 1];
2142 vrc = RTManifestEntryQueryAttr(m->hOurManifest, m->strOvfManifestEntry.c_str(), NULL, RTMANIFEST_ATTR_ANY,
2143 szDigest, sizeof(szDigest), &fType);
2144 if (RT_SUCCESS(vrc))
2145 vrc = RTManifestEntrySetAttr(m->hTheirManifest, m->strOvfManifestEntry.c_str(),
2146 NULL /*pszAttr*/, szDigest, fType);
2147 if (RT_FAILURE(vrc))
2148 return setError(VBOX_E_IPRT_ERROR, tr("Error fudging missing OVF digest in manifest: %Rrc"), vrc);
2149 }
2150
2151 /*
2152 * Compare with the digests we've created while read/processing the import.
2153 *
2154 * We specify the RTMANIFEST_EQUALS_IGN_MISSING_ATTRS to ignore attributes
2155 * (SHA1, SHA256, etc) that are only present in one of the manifests, as long
2156 * as each entry has at least one common attribute that we can check. This
2157 * is important for the OVF in OVAs, for which we generates several digests
2158 * since we don't know which are actually used in the manifest (OVF comes
2159 * first in an OVA, then manifest).
2160 */
2161 char szErr[256];
2162 vrc = RTManifestEqualsEx(m->hTheirManifest, m->hOurManifest, NULL /*papszIgnoreEntries*/,
2163 NULL /*papszIgnoreAttrs*/, RTMANIFEST_EQUALS_IGN_MISSING_ATTRS, szErr, sizeof(szErr));
2164 if (RT_SUCCESS(vrc))
2165 hrc = S_OK;
2166 else
2167 hrc = setErrorVrc(vrc, tr("Digest mismatch (%Rrc): %s"), vrc, szErr);
2168 }
2169
2170 NOREF(stack);
2171 LogFlowThisFunc(("returns %Rhrc\n", hrc));
2172 return hrc;
2173}
2174
2175/**
2176 * Helper that converts VirtualSystem attachment values into VirtualBox attachment values.
2177 * Throws HRESULT values on errors!
2178 *
2179 * @param hdc in: the HardDiskController structure to attach to.
2180 * @param ulAddressOnParent in: the AddressOnParent parameter from OVF.
2181 * @param controllerType out: the name of the hard disk controller to attach to (e.g. "IDE Controller").
2182 * @param lControllerPort out: the channel (controller port) of the controller to attach to.
2183 * @param lDevice out: the device number to attach to.
2184 */
2185void Appliance::i_convertDiskAttachmentValues(const ovf::HardDiskController &hdc,
2186 uint32_t ulAddressOnParent,
2187 Bstr &controllerType,
2188 int32_t &lControllerPort,
2189 int32_t &lDevice)
2190{
2191 Log(("Appliance::i_convertDiskAttachmentValues: hdc.system=%d, hdc.fPrimary=%d, ulAddressOnParent=%d\n",
2192 hdc.system,
2193 hdc.fPrimary,
2194 ulAddressOnParent));
2195
2196 switch (hdc.system)
2197 {
2198 case ovf::HardDiskController::IDE:
2199 // For the IDE bus, the port parameter can be either 0 or 1, to specify the primary
2200 // or secondary IDE controller, respectively. For the primary controller of the IDE bus,
2201 // the device number can be either 0 or 1, to specify the master or the slave device,
2202 // respectively. For the secondary IDE controller, the device number is always 1 because
2203 // the master device is reserved for the CD-ROM drive.
2204 controllerType = Bstr("IDE Controller");
2205 switch (ulAddressOnParent)
2206 {
2207 case 0: // master
2208 if (!hdc.fPrimary)
2209 {
2210 // secondary master
2211 lControllerPort = (long)1;
2212 lDevice = (long)0;
2213 }
2214 else // primary master
2215 {
2216 lControllerPort = (long)0;
2217 lDevice = (long)0;
2218 }
2219 break;
2220
2221 case 1: // slave
2222 if (!hdc.fPrimary)
2223 {
2224 // secondary slave
2225 lControllerPort = (long)1;
2226 lDevice = (long)1;
2227 }
2228 else // primary slave
2229 {
2230 lControllerPort = (long)0;
2231 lDevice = (long)1;
2232 }
2233 break;
2234
2235 // used by older VBox exports
2236 case 2: // interpret this as secondary master
2237 lControllerPort = (long)1;
2238 lDevice = (long)0;
2239 break;
2240
2241 // used by older VBox exports
2242 case 3: // interpret this as secondary slave
2243 lControllerPort = (long)1;
2244 lDevice = (long)1;
2245 break;
2246
2247 default:
2248 throw setError(VBOX_E_NOT_SUPPORTED,
2249 tr("Invalid channel %RI16 specified; IDE controllers support only 0, 1 or 2"),
2250 ulAddressOnParent);
2251 break;
2252 }
2253 break;
2254
2255 case ovf::HardDiskController::SATA:
2256 controllerType = Bstr("SATA Controller");
2257 lControllerPort = (long)ulAddressOnParent;
2258 lDevice = (long)0;
2259 break;
2260
2261 case ovf::HardDiskController::SCSI:
2262 {
2263 if(hdc.strControllerType.compare("lsilogicsas")==0)
2264 controllerType = Bstr("SAS Controller");
2265 else
2266 controllerType = Bstr("SCSI Controller");
2267 lControllerPort = (long)ulAddressOnParent;
2268 lDevice = (long)0;
2269 }
2270 break;
2271
2272 default: break;
2273 }
2274
2275 Log(("=> lControllerPort=%d, lDevice=%d\n", lControllerPort, lDevice));
2276}
2277
2278/**
2279 * Imports one disk image.
2280 *
2281 * This is common code shared between
2282 * -- i_importMachineGeneric() for the OVF case; in that case the information comes from
2283 * the OVF virtual systems;
2284 * -- i_importVBoxMachine(); in that case, the information comes from the <vbox:Machine>
2285 * tag.
2286 *
2287 * Both ways of describing machines use the OVF disk references section, so in both cases
2288 * the caller needs to pass in the ovf::DiskImage structure from ovfreader.cpp.
2289 *
2290 * As a result, in both cases, if di.strHref is empty, we create a new disk as per the OVF
2291 * spec, even though this cannot really happen in the vbox:Machine case since such data
2292 * would never have been exported.
2293 *
2294 * This advances stack.pProgress by one operation with the disk's weight.
2295 *
2296 * @param di ovfreader.cpp structure describing the disk image from the OVF that is to be imported
2297 * @param strTargetPath Where to create the target image.
2298 * @param pTargetHD out: The newly created target disk. This also gets pushed on stack.llHardDisksCreated for cleanup.
2299 * @param stack
2300 */
2301void Appliance::i_importOneDiskImage(const ovf::DiskImage &di,
2302 Utf8Str *pStrDstPath,
2303 ComObjPtr<Medium> &pTargetHD,
2304 ImportStack &stack)
2305{
2306 ComObjPtr<Progress> pProgress;
2307 pProgress.createObject();
2308 HRESULT rc = pProgress->init(mVirtualBox,
2309 static_cast<IAppliance*>(this),
2310 BstrFmt(tr("Creating medium '%s'"),
2311 pStrDstPath->c_str()).raw(),
2312 TRUE);
2313 if (FAILED(rc)) throw rc;
2314
2315 /* Get the system properties. */
2316 SystemProperties *pSysProps = mVirtualBox->i_getSystemProperties();
2317
2318 /* Keep the source file ref handy for later. */
2319 const Utf8Str &strSourceOVF = di.strHref;
2320
2321 /* Construct source file path */
2322 Utf8Str strSrcFilePath;
2323 if (stack.hVfsFssOva != NIL_RTVFSFSSTREAM)
2324 strSrcFilePath = strSourceOVF;
2325 else
2326 {
2327 strSrcFilePath = stack.strSourceDir;
2328 strSrcFilePath.append(RTPATH_SLASH_STR);
2329 strSrcFilePath.append(strSourceOVF);
2330 }
2331
2332 /* First of all check if the path is an UUID. If so, the user like to
2333 * import the disk into an existing path. This is useful for iSCSI for
2334 * example. */
2335 RTUUID uuid;
2336 int vrc = RTUuidFromStr(&uuid, pStrDstPath->c_str());
2337 if (vrc == VINF_SUCCESS)
2338 {
2339 rc = mVirtualBox->i_findHardDiskById(Guid(uuid), true, &pTargetHD);
2340 if (FAILED(rc)) throw rc;
2341 }
2342 else
2343 {
2344 RTVFSIOSTREAM hVfsIosSrc = NIL_RTVFSIOSTREAM;
2345
2346 /* check read file to GZIP compression */
2347 bool const fGzipped = di.strCompression.compare("gzip",Utf8Str::CaseInsensitive) == 0;
2348 Utf8Str strDeleteTemp;
2349 try
2350 {
2351 Utf8Str strTrgFormat = "VMDK";
2352 ComObjPtr<MediumFormat> trgFormat;
2353 Bstr bstrFormatName;
2354 ULONG lCabs = 0;
2355
2356 char *pszSuff = RTPathSuffix(pStrDstPath->c_str());
2357 if (pszSuff != NULL)
2358 {
2359 /*
2360 * Figure out which format the user like to have. Default is VMDK
2361 * or it can be VDI if according command-line option is set
2362 */
2363
2364 /*
2365 * We need a proper target format
2366 * if target format has been changed by user via GUI import wizard
2367 * or via VBoxManage import command (option --importtovdi)
2368 * then we need properly process such format like ISO
2369 * Because there is no conversion ISO to VDI
2370 */
2371 trgFormat = pSysProps->i_mediumFormatFromExtension(++pszSuff);
2372 if (trgFormat.isNull())
2373 throw setError(E_FAIL, tr("Unsupported medium format for disk image '%s'"), di.strHref.c_str());
2374
2375 rc = trgFormat->COMGETTER(Name)(bstrFormatName.asOutParam());
2376 if (FAILED(rc)) throw rc;
2377
2378 strTrgFormat = Utf8Str(bstrFormatName);
2379
2380 if ( m->optListImport.contains(ImportOptions_ImportToVDI)
2381 && strTrgFormat.compare("RAW", Utf8Str::CaseInsensitive) != 0)
2382 {
2383 /* change the target extension */
2384 strTrgFormat = "vdi";
2385 trgFormat = pSysProps->i_mediumFormatFromExtension(strTrgFormat);
2386 *pStrDstPath = pStrDstPath->stripSuffix();
2387 *pStrDstPath = pStrDstPath->append(".");
2388 *pStrDstPath = pStrDstPath->append(strTrgFormat.c_str());
2389 }
2390
2391 /* Check the capabilities. We need create capabilities. */
2392 lCabs = 0;
2393 com::SafeArray <MediumFormatCapabilities_T> mediumFormatCap;
2394 rc = trgFormat->COMGETTER(Capabilities)(ComSafeArrayAsOutParam(mediumFormatCap));
2395
2396 if (FAILED(rc))
2397 throw rc;
2398
2399 for (ULONG j = 0; j < mediumFormatCap.size(); j++)
2400 lCabs |= mediumFormatCap[j];
2401
2402 if ( !(lCabs & MediumFormatCapabilities_CreateFixed)
2403 && !(lCabs & MediumFormatCapabilities_CreateDynamic) )
2404 throw setError(VBOX_E_NOT_SUPPORTED,
2405 tr("Could not find a valid medium format for the target disk '%s'"),
2406 pStrDstPath->c_str());
2407 }
2408 else
2409 {
2410 throw setError(VBOX_E_FILE_ERROR,
2411 tr("The target disk '%s' has no extension "),
2412 pStrDstPath->c_str(), VERR_INVALID_NAME);
2413 }
2414
2415 /* Create an IMedium object. */
2416 pTargetHD.createObject();
2417
2418 /*CD/DVD case*/
2419 if (strTrgFormat.compare("RAW", Utf8Str::CaseInsensitive) == 0)
2420 {
2421 try
2422 {
2423 if (fGzipped)
2424 i_importDecompressFile(stack, strSrcFilePath, *pStrDstPath, strSourceOVF.c_str());
2425 else
2426 i_importCopyFile(stack, strSrcFilePath, *pStrDstPath, strSourceOVF.c_str());
2427 }
2428 catch (HRESULT /*arc*/)
2429 {
2430 throw;
2431 }
2432
2433 /* Advance to the next operation. */
2434 /* operation's weight, as set up with the IProgress originally */
2435 stack.pProgress->SetNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"),
2436 RTPathFilename(strSourceOVF.c_str())).raw(),
2437 di.ulSuggestedSizeMB);
2438 }
2439 else/* HDD case*/
2440 {
2441 rc = pTargetHD->init(mVirtualBox,
2442 strTrgFormat,
2443 *pStrDstPath,
2444 Guid::Empty /* media registry: none yet */,
2445 DeviceType_HardDisk);
2446 if (FAILED(rc)) throw rc;
2447
2448 /* Now create an empty hard disk. */
2449 rc = mVirtualBox->CreateMedium(Bstr(strTrgFormat).raw(),
2450 Bstr(*pStrDstPath).raw(),
2451 AccessMode_ReadWrite, DeviceType_HardDisk,
2452 ComPtr<IMedium>(pTargetHD).asOutParam());
2453 if (FAILED(rc)) throw rc;
2454
2455 /* If strHref is empty we have to create a new file. */
2456 if (strSourceOVF.isEmpty())
2457 {
2458 com::SafeArray<MediumVariant_T> mediumVariant;
2459 mediumVariant.push_back(MediumVariant_Standard);
2460
2461 /* Kick of the creation of a dynamic growing disk image with the given capacity. */
2462 rc = pTargetHD->CreateBaseStorage(di.iCapacity / _1M,
2463 ComSafeArrayAsInParam(mediumVariant),
2464 ComPtr<IProgress>(pProgress).asOutParam());
2465 if (FAILED(rc)) throw rc;
2466
2467 /* Advance to the next operation. */
2468 /* operation's weight, as set up with the IProgress originally */
2469 stack.pProgress->SetNextOperation(BstrFmt(tr("Creating disk image '%s'"),
2470 pStrDstPath->c_str()).raw(),
2471 di.ulSuggestedSizeMB);
2472 }
2473 else
2474 {
2475 /* We need a proper source format description */
2476 /* Which format to use? */
2477 ComObjPtr<MediumFormat> srcFormat;
2478 rc = i_findMediumFormatFromDiskImage(di, srcFormat);
2479 if (FAILED(rc))
2480 throw setError(VBOX_E_NOT_SUPPORTED,
2481 tr("Could not find a valid medium format for the source disk '%s' "
2482 "Check correctness of the image format URL in the OVF description file "
2483 "or extension of the image"),
2484 RTPathFilename(strSourceOVF.c_str()));
2485
2486 /* If gzipped, decompress the GZIP file and save a new file in the target path */
2487 if (fGzipped)
2488 {
2489 Utf8Str strTargetFilePath(*pStrDstPath);
2490 strTargetFilePath.stripFilename();
2491 strTargetFilePath.append(RTPATH_SLASH_STR);
2492 strTargetFilePath.append("temp_");
2493 strTargetFilePath.append(RTPathFilename(strSrcFilePath.c_str()));
2494 strDeleteTemp = strTargetFilePath;
2495
2496 i_importDecompressFile(stack, strSrcFilePath, strTargetFilePath, strSourceOVF.c_str());
2497
2498 /* Correct the source and the target with the actual values */
2499 strSrcFilePath = strTargetFilePath;
2500
2501 /* Open the new source file. */
2502 vrc = RTVfsIoStrmOpenNormal(strSrcFilePath.c_str(), RTFILE_O_READ | RTFILE_O_DENY_NONE | RTFILE_O_OPEN,
2503 &hVfsIosSrc);
2504 if (RT_FAILURE(vrc))
2505 throw setErrorVrc(vrc, tr("Error opening decompressed image file '%s' (%Rrc)"),
2506 strSrcFilePath.c_str(), vrc);
2507 }
2508 else
2509 hVfsIosSrc = i_importOpenSourceFile(stack, strSrcFilePath, strSourceOVF.c_str());
2510
2511 /* Start the source image cloning operation. */
2512 ComObjPtr<Medium> nullParent;
2513 rc = pTargetHD->i_importFile(strSrcFilePath.c_str(),
2514 srcFormat,
2515 MediumVariant_Standard,
2516 hVfsIosSrc,
2517 nullParent,
2518 pProgress);
2519 RTVfsIoStrmRelease(hVfsIosSrc);
2520 hVfsIosSrc = NIL_RTVFSIOSTREAM;
2521 if (FAILED(rc))
2522 throw rc;
2523
2524 /* Advance to the next operation. */
2525 /* operation's weight, as set up with the IProgress originally */
2526 stack.pProgress->SetNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"),
2527 RTPathFilename(strSourceOVF.c_str())).raw(),
2528 di.ulSuggestedSizeMB);
2529 }
2530
2531 /* Now wait for the background disk operation to complete; this throws
2532 * HRESULTs on error. */
2533 ComPtr<IProgress> pp(pProgress);
2534 i_waitForAsyncProgress(stack.pProgress, pp);
2535 }
2536 }
2537 catch (...)
2538 {
2539 if (strDeleteTemp.isNotEmpty())
2540 RTFileDelete(strDeleteTemp.c_str());
2541 throw;
2542 }
2543
2544 /* Make sure the source file is closed. */
2545 if (hVfsIosSrc != NIL_RTVFSIOSTREAM)
2546 RTVfsIoStrmRelease(hVfsIosSrc);
2547
2548 /*
2549 * Delete the temp gunzip result, if any.
2550 */
2551 if (strDeleteTemp.isNotEmpty())
2552 {
2553 vrc = RTFileDelete(strSrcFilePath.c_str());
2554 if (RT_FAILURE(vrc))
2555 setWarning(VBOX_E_FILE_ERROR,
2556 tr("Failed to delete the temporary file '%s' (%Rrc)"), strSrcFilePath.c_str(), vrc);
2557 }
2558 }
2559}
2560
2561/**
2562 * Imports one OVF virtual system (described by the given ovf::VirtualSystem and VirtualSystemDescription)
2563 * into VirtualBox by creating an IMachine instance, which is returned.
2564 *
2565 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
2566 * up any leftovers from this function. For this, the given ImportStack instance has received information
2567 * about what needs cleaning up (to support rollback).
2568 *
2569 * @param vsysThis OVF virtual system (machine) to import.
2570 * @param vsdescThis Matching virtual system description (machine) to import.
2571 * @param pNewMachine out: Newly created machine.
2572 * @param stack Cleanup stack for when this throws.
2573 */
2574void Appliance::i_importMachineGeneric(const ovf::VirtualSystem &vsysThis,
2575 ComObjPtr<VirtualSystemDescription> &vsdescThis,
2576 ComPtr<IMachine> &pNewMachine,
2577 ImportStack &stack)
2578{
2579 LogFlowFuncEnter();
2580 HRESULT rc;
2581
2582 // Get the instance of IGuestOSType which matches our string guest OS type so we
2583 // can use recommended defaults for the new machine where OVF doesn't provide any
2584 ComPtr<IGuestOSType> osType;
2585 rc = mVirtualBox->GetGuestOSType(Bstr(stack.strOsTypeVBox).raw(), osType.asOutParam());
2586 if (FAILED(rc)) throw rc;
2587
2588 /* Create the machine */
2589 SafeArray<BSTR> groups; /* no groups */
2590 rc = mVirtualBox->CreateMachine(NULL, /* machine name: use default */
2591 Bstr(stack.strNameVBox).raw(),
2592 ComSafeArrayAsInParam(groups),
2593 Bstr(stack.strOsTypeVBox).raw(),
2594 NULL, /* aCreateFlags */
2595 pNewMachine.asOutParam());
2596 if (FAILED(rc)) throw rc;
2597
2598 // set the description
2599 if (!stack.strDescription.isEmpty())
2600 {
2601 rc = pNewMachine->COMSETTER(Description)(Bstr(stack.strDescription).raw());
2602 if (FAILED(rc)) throw rc;
2603 }
2604
2605 // CPU count
2606 rc = pNewMachine->COMSETTER(CPUCount)(stack.cCPUs);
2607 if (FAILED(rc)) throw rc;
2608
2609 if (stack.fForceHWVirt)
2610 {
2611 rc = pNewMachine->SetHWVirtExProperty(HWVirtExPropertyType_Enabled, TRUE);
2612 if (FAILED(rc)) throw rc;
2613 }
2614
2615 // RAM
2616 rc = pNewMachine->COMSETTER(MemorySize)(stack.ulMemorySizeMB);
2617 if (FAILED(rc)) throw rc;
2618
2619 /* VRAM */
2620 /* Get the recommended VRAM for this guest OS type */
2621 ULONG vramVBox;
2622 rc = osType->COMGETTER(RecommendedVRAM)(&vramVBox);
2623 if (FAILED(rc)) throw rc;
2624
2625 /* Set the VRAM */
2626 rc = pNewMachine->COMSETTER(VRAMSize)(vramVBox);
2627 if (FAILED(rc)) throw rc;
2628
2629 // I/O APIC: Generic OVF has no setting for this. Enable it if we
2630 // import a Windows VM because if if Windows was installed without IOAPIC,
2631 // it will not mind finding an one later on, but if Windows was installed
2632 // _with_ an IOAPIC, it will bluescreen if it's not found
2633 if (!stack.fForceIOAPIC)
2634 {
2635 Bstr bstrFamilyId;
2636 rc = osType->COMGETTER(FamilyId)(bstrFamilyId.asOutParam());
2637 if (FAILED(rc)) throw rc;
2638 if (bstrFamilyId == "Windows")
2639 stack.fForceIOAPIC = true;
2640 }
2641
2642 if (stack.fForceIOAPIC)
2643 {
2644 ComPtr<IBIOSSettings> pBIOSSettings;
2645 rc = pNewMachine->COMGETTER(BIOSSettings)(pBIOSSettings.asOutParam());
2646 if (FAILED(rc)) throw rc;
2647
2648 rc = pBIOSSettings->COMSETTER(IOAPICEnabled)(TRUE);
2649 if (FAILED(rc)) throw rc;
2650 }
2651
2652 if (!stack.strAudioAdapter.isEmpty())
2653 if (stack.strAudioAdapter.compare("null", Utf8Str::CaseInsensitive) != 0)
2654 {
2655 uint32_t audio = RTStrToUInt32(stack.strAudioAdapter.c_str()); // should be 0 for AC97
2656 ComPtr<IAudioAdapter> audioAdapter;
2657 rc = pNewMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam());
2658 if (FAILED(rc)) throw rc;
2659 rc = audioAdapter->COMSETTER(Enabled)(true);
2660 if (FAILED(rc)) throw rc;
2661 rc = audioAdapter->COMSETTER(AudioController)(static_cast<AudioControllerType_T>(audio));
2662 if (FAILED(rc)) throw rc;
2663 }
2664
2665#ifdef VBOX_WITH_USB
2666 /* USB Controller */
2667 if (stack.fUSBEnabled)
2668 {
2669 ComPtr<IUSBController> usbController;
2670 rc = pNewMachine->AddUSBController(Bstr("OHCI").raw(), USBControllerType_OHCI, usbController.asOutParam());
2671 if (FAILED(rc)) throw rc;
2672 }
2673#endif /* VBOX_WITH_USB */
2674
2675 /* Change the network adapters */
2676 uint32_t maxNetworkAdapters = Global::getMaxNetworkAdapters(ChipsetType_PIIX3);
2677
2678 std::list<VirtualSystemDescriptionEntry*> vsdeNW = vsdescThis->i_findByType(VirtualSystemDescriptionType_NetworkAdapter);
2679 if (vsdeNW.empty())
2680 {
2681 /* No network adapters, so we have to disable our default one */
2682 ComPtr<INetworkAdapter> nwVBox;
2683 rc = pNewMachine->GetNetworkAdapter(0, nwVBox.asOutParam());
2684 if (FAILED(rc)) throw rc;
2685 rc = nwVBox->COMSETTER(Enabled)(false);
2686 if (FAILED(rc)) throw rc;
2687 }
2688 else if (vsdeNW.size() > maxNetworkAdapters)
2689 throw setError(VBOX_E_FILE_ERROR,
2690 tr("Too many network adapters: OVF requests %d network adapters, "
2691 "but VirtualBox only supports %d"),
2692 vsdeNW.size(), maxNetworkAdapters);
2693 else
2694 {
2695 list<VirtualSystemDescriptionEntry*>::const_iterator nwIt;
2696 size_t a = 0;
2697 for (nwIt = vsdeNW.begin();
2698 nwIt != vsdeNW.end();
2699 ++nwIt, ++a)
2700 {
2701 const VirtualSystemDescriptionEntry* pvsys = *nwIt;
2702
2703 const Utf8Str &nwTypeVBox = pvsys->strVBoxCurrent;
2704 uint32_t tt1 = RTStrToUInt32(nwTypeVBox.c_str());
2705 ComPtr<INetworkAdapter> pNetworkAdapter;
2706 rc = pNewMachine->GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
2707 if (FAILED(rc)) throw rc;
2708 /* Enable the network card & set the adapter type */
2709 rc = pNetworkAdapter->COMSETTER(Enabled)(true);
2710 if (FAILED(rc)) throw rc;
2711 rc = pNetworkAdapter->COMSETTER(AdapterType)(static_cast<NetworkAdapterType_T>(tt1));
2712 if (FAILED(rc)) throw rc;
2713
2714 // default is NAT; change to "bridged" if extra conf says so
2715 if (pvsys->strExtraConfigCurrent.endsWith("type=Bridged", Utf8Str::CaseInsensitive))
2716 {
2717 /* Attach to the right interface */
2718 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_Bridged);
2719 if (FAILED(rc)) throw rc;
2720 ComPtr<IHost> host;
2721 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
2722 if (FAILED(rc)) throw rc;
2723 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
2724 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
2725 if (FAILED(rc)) throw rc;
2726 // We search for the first host network interface which
2727 // is usable for bridged networking
2728 for (size_t j = 0;
2729 j < nwInterfaces.size();
2730 ++j)
2731 {
2732 HostNetworkInterfaceType_T itype;
2733 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
2734 if (FAILED(rc)) throw rc;
2735 if (itype == HostNetworkInterfaceType_Bridged)
2736 {
2737 Bstr name;
2738 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
2739 if (FAILED(rc)) throw rc;
2740 /* Set the interface name to attach to */
2741 rc = pNetworkAdapter->COMSETTER(BridgedInterface)(name.raw());
2742 if (FAILED(rc)) throw rc;
2743 break;
2744 }
2745 }
2746 }
2747 /* Next test for host only interfaces */
2748 else if (pvsys->strExtraConfigCurrent.endsWith("type=HostOnly", Utf8Str::CaseInsensitive))
2749 {
2750 /* Attach to the right interface */
2751 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_HostOnly);
2752 if (FAILED(rc)) throw rc;
2753 ComPtr<IHost> host;
2754 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
2755 if (FAILED(rc)) throw rc;
2756 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
2757 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
2758 if (FAILED(rc)) throw rc;
2759 // We search for the first host network interface which
2760 // is usable for host only networking
2761 for (size_t j = 0;
2762 j < nwInterfaces.size();
2763 ++j)
2764 {
2765 HostNetworkInterfaceType_T itype;
2766 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
2767 if (FAILED(rc)) throw rc;
2768 if (itype == HostNetworkInterfaceType_HostOnly)
2769 {
2770 Bstr name;
2771 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
2772 if (FAILED(rc)) throw rc;
2773 /* Set the interface name to attach to */
2774 rc = pNetworkAdapter->COMSETTER(HostOnlyInterface)(name.raw());
2775 if (FAILED(rc)) throw rc;
2776 break;
2777 }
2778 }
2779 }
2780 /* Next test for internal interfaces */
2781 else if (pvsys->strExtraConfigCurrent.endsWith("type=Internal", Utf8Str::CaseInsensitive))
2782 {
2783 /* Attach to the right interface */
2784 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_Internal);
2785 if (FAILED(rc)) throw rc;
2786 }
2787 /* Next test for Generic interfaces */
2788 else if (pvsys->strExtraConfigCurrent.endsWith("type=Generic", Utf8Str::CaseInsensitive))
2789 {
2790 /* Attach to the right interface */
2791 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_Generic);
2792 if (FAILED(rc)) throw rc;
2793 }
2794
2795 /* Next test for NAT network interfaces */
2796 else if (pvsys->strExtraConfigCurrent.endsWith("type=NATNetwork", Utf8Str::CaseInsensitive))
2797 {
2798 /* Attach to the right interface */
2799 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_NATNetwork);
2800 if (FAILED(rc)) throw rc;
2801 com::SafeIfaceArray<INATNetwork> nwNATNetworks;
2802 rc = mVirtualBox->COMGETTER(NATNetworks)(ComSafeArrayAsOutParam(nwNATNetworks));
2803 if (FAILED(rc)) throw rc;
2804 // Pick the first NAT network (if there is any)
2805 if (nwNATNetworks.size())
2806 {
2807 Bstr name;
2808 rc = nwNATNetworks[0]->COMGETTER(NetworkName)(name.asOutParam());
2809 if (FAILED(rc)) throw rc;
2810 /* Set the NAT network name to attach to */
2811 rc = pNetworkAdapter->COMSETTER(NATNetwork)(name.raw());
2812 if (FAILED(rc)) throw rc;
2813 break;
2814 }
2815 }
2816 }
2817 }
2818
2819 // IDE Hard disk controller
2820 std::list<VirtualSystemDescriptionEntry*> vsdeHDCIDE =
2821 vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskControllerIDE);
2822 /*
2823 * In OVF (at least VMware's version of it), an IDE controller has two ports,
2824 * so VirtualBox's single IDE controller with two channels and two ports each counts as
2825 * two OVF IDE controllers -- so we accept one or two such IDE controllers
2826 */
2827 size_t cIDEControllers = vsdeHDCIDE.size();
2828 if (cIDEControllers > 2)
2829 throw setError(VBOX_E_FILE_ERROR,
2830 tr("Too many IDE controllers in OVF; import facility only supports two"));
2831 if (!vsdeHDCIDE.empty())
2832 {
2833 // one or two IDE controllers present in OVF: add one VirtualBox controller
2834 ComPtr<IStorageController> pController;
2835 rc = pNewMachine->AddStorageController(Bstr("IDE Controller").raw(), StorageBus_IDE, pController.asOutParam());
2836 if (FAILED(rc)) throw rc;
2837
2838 const char *pcszIDEType = vsdeHDCIDE.front()->strVBoxCurrent.c_str();
2839 if (!strcmp(pcszIDEType, "PIIX3"))
2840 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX3);
2841 else if (!strcmp(pcszIDEType, "PIIX4"))
2842 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX4);
2843 else if (!strcmp(pcszIDEType, "ICH6"))
2844 rc = pController->COMSETTER(ControllerType)(StorageControllerType_ICH6);
2845 else
2846 throw setError(VBOX_E_FILE_ERROR,
2847 tr("Invalid IDE controller type \"%s\""),
2848 pcszIDEType);
2849 if (FAILED(rc)) throw rc;
2850 }
2851
2852 /* Hard disk controller SATA */
2853 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSATA =
2854 vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskControllerSATA);
2855 if (vsdeHDCSATA.size() > 1)
2856 throw setError(VBOX_E_FILE_ERROR,
2857 tr("Too many SATA controllers in OVF; import facility only supports one"));
2858 if (!vsdeHDCSATA.empty())
2859 {
2860 ComPtr<IStorageController> pController;
2861 const Utf8Str &hdcVBox = vsdeHDCSATA.front()->strVBoxCurrent;
2862 if (hdcVBox == "AHCI")
2863 {
2864 rc = pNewMachine->AddStorageController(Bstr("SATA Controller").raw(),
2865 StorageBus_SATA,
2866 pController.asOutParam());
2867 if (FAILED(rc)) throw rc;
2868 }
2869 else
2870 throw setError(VBOX_E_FILE_ERROR,
2871 tr("Invalid SATA controller type \"%s\""),
2872 hdcVBox.c_str());
2873 }
2874
2875 /* Hard disk controller SCSI */
2876 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSCSI =
2877 vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskControllerSCSI);
2878 if (vsdeHDCSCSI.size() > 1)
2879 throw setError(VBOX_E_FILE_ERROR,
2880 tr("Too many SCSI controllers in OVF; import facility only supports one"));
2881 if (!vsdeHDCSCSI.empty())
2882 {
2883 ComPtr<IStorageController> pController;
2884 Bstr bstrName(L"SCSI Controller");
2885 StorageBus_T busType = StorageBus_SCSI;
2886 StorageControllerType_T controllerType;
2887 const Utf8Str &hdcVBox = vsdeHDCSCSI.front()->strVBoxCurrent;
2888 if (hdcVBox == "LsiLogic")
2889 controllerType = StorageControllerType_LsiLogic;
2890 else if (hdcVBox == "LsiLogicSas")
2891 {
2892 // OVF treats LsiLogicSas as a SCSI controller but VBox considers it a class of its own
2893 bstrName = L"SAS Controller";
2894 busType = StorageBus_SAS;
2895 controllerType = StorageControllerType_LsiLogicSas;
2896 }
2897 else if (hdcVBox == "BusLogic")
2898 controllerType = StorageControllerType_BusLogic;
2899 else
2900 throw setError(VBOX_E_FILE_ERROR,
2901 tr("Invalid SCSI controller type \"%s\""),
2902 hdcVBox.c_str());
2903
2904 rc = pNewMachine->AddStorageController(bstrName.raw(), busType, pController.asOutParam());
2905 if (FAILED(rc)) throw rc;
2906 rc = pController->COMSETTER(ControllerType)(controllerType);
2907 if (FAILED(rc)) throw rc;
2908 }
2909
2910 /* Hard disk controller SAS */
2911 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSAS =
2912 vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskControllerSAS);
2913 if (vsdeHDCSAS.size() > 1)
2914 throw setError(VBOX_E_FILE_ERROR,
2915 tr("Too many SAS controllers in OVF; import facility only supports one"));
2916 if (!vsdeHDCSAS.empty())
2917 {
2918 ComPtr<IStorageController> pController;
2919 rc = pNewMachine->AddStorageController(Bstr(L"SAS Controller").raw(),
2920 StorageBus_SAS,
2921 pController.asOutParam());
2922 if (FAILED(rc)) throw rc;
2923 rc = pController->COMSETTER(ControllerType)(StorageControllerType_LsiLogicSas);
2924 if (FAILED(rc)) throw rc;
2925 }
2926
2927 /* Now its time to register the machine before we add any hard disks */
2928 rc = mVirtualBox->RegisterMachine(pNewMachine);
2929 if (FAILED(rc)) throw rc;
2930
2931 // store new machine for roll-back in case of errors
2932 Bstr bstrNewMachineId;
2933 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
2934 if (FAILED(rc)) throw rc;
2935 Guid uuidNewMachine(bstrNewMachineId);
2936 m->llGuidsMachinesCreated.push_back(uuidNewMachine);
2937
2938 // Add floppies and CD-ROMs to the appropriate controllers.
2939 std::list<VirtualSystemDescriptionEntry*> vsdeFloppy = vsdescThis->i_findByType(VirtualSystemDescriptionType_Floppy);
2940 if (vsdeFloppy.size() > 1)
2941 throw setError(VBOX_E_FILE_ERROR,
2942 tr("Too many floppy controllers in OVF; import facility only supports one"));
2943 std::list<VirtualSystemDescriptionEntry*> vsdeCDROM = vsdescThis->i_findByType(VirtualSystemDescriptionType_CDROM);
2944 if ( !vsdeFloppy.empty()
2945 || !vsdeCDROM.empty()
2946 )
2947 {
2948 // If there's an error here we need to close the session, so
2949 // we need another try/catch block.
2950
2951 try
2952 {
2953 // to attach things we need to open a session for the new machine
2954 rc = pNewMachine->LockMachine(stack.pSession, LockType_Write);
2955 if (FAILED(rc)) throw rc;
2956 stack.fSessionOpen = true;
2957
2958 ComPtr<IMachine> sMachine;
2959 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
2960 if (FAILED(rc)) throw rc;
2961
2962 // floppy first
2963 if (vsdeFloppy.size() == 1)
2964 {
2965 ComPtr<IStorageController> pController;
2966 rc = sMachine->AddStorageController(Bstr("Floppy Controller").raw(),
2967 StorageBus_Floppy,
2968 pController.asOutParam());
2969 if (FAILED(rc)) throw rc;
2970
2971 Bstr bstrName;
2972 rc = pController->COMGETTER(Name)(bstrName.asOutParam());
2973 if (FAILED(rc)) throw rc;
2974
2975 // this is for rollback later
2976 MyHardDiskAttachment mhda;
2977 mhda.pMachine = pNewMachine;
2978 mhda.controllerType = bstrName;
2979 mhda.lControllerPort = 0;
2980 mhda.lDevice = 0;
2981
2982 Log(("Attaching floppy\n"));
2983
2984 rc = sMachine->AttachDevice(mhda.controllerType.raw(),
2985 mhda.lControllerPort,
2986 mhda.lDevice,
2987 DeviceType_Floppy,
2988 NULL);
2989 if (FAILED(rc)) throw rc;
2990
2991 stack.llHardDiskAttachments.push_back(mhda);
2992 }
2993
2994 rc = sMachine->SaveSettings();
2995 if (FAILED(rc)) throw rc;
2996
2997 // only now that we're done with all disks, close the session
2998 rc = stack.pSession->UnlockMachine();
2999 if (FAILED(rc)) throw rc;
3000 stack.fSessionOpen = false;
3001 }
3002 catch(HRESULT aRC)
3003 {
3004 com::ErrorInfo info;
3005
3006 if (stack.fSessionOpen)
3007 stack.pSession->UnlockMachine();
3008
3009 if (info.isFullAvailable())
3010 throw setError(aRC, Utf8Str(info.getText()).c_str());
3011 else
3012 throw setError(aRC, "Unknown error during OVF import");
3013 }
3014 }
3015
3016 // create the hard disks & connect them to the appropriate controllers
3017 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskImage);
3018 if (!avsdeHDs.empty())
3019 {
3020 // If there's an error here we need to close the session, so
3021 // we need another try/catch block.
3022 try
3023 {
3024#ifdef LOG_ENABLED
3025 if (LogIsEnabled())
3026 {
3027 size_t i = 0;
3028 for (list<VirtualSystemDescriptionEntry*>::const_iterator itHD = avsdeHDs.begin();
3029 itHD != avsdeHDs.end(); ++itHD, i++)
3030 Log(("avsdeHDs[%zu]: strRef=%s strOvf=%s\n", i, (*itHD)->strRef.c_str(), (*itHD)->strOvf.c_str()));
3031 i = 0;
3032 for (ovf::DiskImagesMap::const_iterator itDisk = stack.mapDisks.begin(); itDisk != stack.mapDisks.end(); ++itDisk)
3033 Log(("mapDisks[%zu]: strDiskId=%s strHref=%s\n",
3034 i, itDisk->second.strDiskId.c_str(), itDisk->second.strHref.c_str()));
3035
3036 }
3037#endif
3038
3039 // to attach things we need to open a session for the new machine
3040 rc = pNewMachine->LockMachine(stack.pSession, LockType_Write);
3041 if (FAILED(rc)) throw rc;
3042 stack.fSessionOpen = true;
3043
3044 /* get VM name from virtual system description. Only one record is possible (size of list is equal 1). */
3045 std::list<VirtualSystemDescriptionEntry*> vmName = vsdescThis->i_findByType(VirtualSystemDescriptionType_Name);
3046 std::list<VirtualSystemDescriptionEntry*>::iterator vmNameIt = vmName.begin();
3047 VirtualSystemDescriptionEntry* vmNameEntry = *vmNameIt;
3048
3049
3050 ovf::DiskImagesMap::const_iterator oit = stack.mapDisks.begin();
3051 std::set<RTCString> disksResolvedNames;
3052
3053 uint32_t cImportedDisks = 0;
3054
3055 while (oit != stack.mapDisks.end() && cImportedDisks != avsdeHDs.size())
3056 {
3057/** @todo r=bird: Most of the code here is duplicated in the other machine
3058 * import method, factor out. */
3059 ovf::DiskImage diCurrent = oit->second;
3060
3061 Log(("diCurrent.strDiskId=%s diCurrent.strHref=%s\n", diCurrent.strDiskId.c_str(), diCurrent.strHref.c_str()));
3062 /* Iterate over all given disk images of the virtual system
3063 * disks description. We need to find the target disk path,
3064 * which could be changed by the user. */
3065 VirtualSystemDescriptionEntry *vsdeTargetHD = NULL;
3066 for (list<VirtualSystemDescriptionEntry*>::const_iterator itHD = avsdeHDs.begin();
3067 itHD != avsdeHDs.end();
3068 ++itHD)
3069 {
3070 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
3071 if (vsdeHD->strRef == diCurrent.strDiskId)
3072 {
3073 vsdeTargetHD = vsdeHD;
3074 break;
3075 }
3076 }
3077 if (!vsdeTargetHD)
3078 {
3079 /* possible case if a disk image belongs to other virtual system (OVF package with multiple VMs inside) */
3080 Log1Warning(("OVA/OVF import: Disk image %s was missed during import of VM %s\n",
3081 oit->first.c_str(), vmNameEntry->strOvf.c_str()));
3082 NOREF(vmNameEntry);
3083 ++oit;
3084 continue;
3085 }
3086
3087 //diCurrent.strDiskId contains the disk identifier (e.g. "vmdisk1"), which should exist
3088 //in the virtual system's disks map under that ID and also in the global images map
3089 ovf::VirtualDisksMap::const_iterator itVDisk = vsysThis.mapVirtualDisks.find(diCurrent.strDiskId);
3090 if (itVDisk == vsysThis.mapVirtualDisks.end())
3091 throw setError(E_FAIL,
3092 tr("Internal inconsistency looking up disk image '%s'"),
3093 diCurrent.strHref.c_str());
3094
3095 /*
3096 * preliminary check availability of the image
3097 * This step is useful if image is placed in the OVA (TAR) package
3098 */
3099 if (stack.hVfsFssOva != NIL_RTVFSFSSTREAM)
3100 {
3101 /* It means that we possibly have imported the storage earlier on the previous loop steps*/
3102 std::set<RTCString>::const_iterator h = disksResolvedNames.find(diCurrent.strHref);
3103 if (h != disksResolvedNames.end())
3104 {
3105 /* Yes, disk name was found, we can skip it*/
3106 ++oit;
3107 continue;
3108 }
3109l_skipped:
3110 rc = i_preCheckImageAvailability(stack);
3111 if (SUCCEEDED(rc))
3112 {
3113 /* current opened file isn't the same as passed one */
3114 if (RTStrICmp(diCurrent.strHref.c_str(), stack.pszOvaLookAheadName) != 0)
3115 {
3116 /* availableImage contains the disk file reference (e.g. "disk1.vmdk"), which should
3117 * exist in the global images map.
3118 * And find the disk from the OVF's disk list */
3119 ovf::DiskImagesMap::const_iterator itDiskImage;
3120 for (itDiskImage = stack.mapDisks.begin();
3121 itDiskImage != stack.mapDisks.end();
3122 itDiskImage++)
3123 if (itDiskImage->second.strHref.compare(stack.pszOvaLookAheadName,
3124 Utf8Str::CaseInsensitive) == 0)
3125 break;
3126 if (itDiskImage == stack.mapDisks.end())
3127 {
3128 LogFunc(("Skipping '%s'\n", stack.pszOvaLookAheadName));
3129 RTVfsIoStrmRelease(stack.claimOvaLookAHead());
3130 goto l_skipped;
3131 }
3132
3133 /* replace with a new found disk image */
3134 diCurrent = *(&itDiskImage->second);
3135
3136 /*
3137 * Again iterate over all given disk images of the virtual system
3138 * disks description using the found disk image
3139 */
3140 for (list<VirtualSystemDescriptionEntry*>::const_iterator itHD = avsdeHDs.begin();
3141 itHD != avsdeHDs.end();
3142 ++itHD)
3143 {
3144 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
3145 if (vsdeHD->strRef == diCurrent.strDiskId)
3146 {
3147 vsdeTargetHD = vsdeHD;
3148 break;
3149 }
3150 }
3151
3152 /*
3153 * in this case it's an error because something is wrong with the OVF description file.
3154 * May be VBox imports OVA package with wrong file sequence inside the archive.
3155 */
3156 if (!vsdeTargetHD)
3157 throw setError(E_FAIL,
3158 tr("Internal inconsistency looking up disk image '%s'"),
3159 diCurrent.strHref.c_str());
3160
3161 itVDisk = vsysThis.mapVirtualDisks.find(diCurrent.strDiskId);
3162 if (itVDisk == vsysThis.mapVirtualDisks.end())
3163 throw setError(E_FAIL,
3164 tr("Internal inconsistency looking up disk image '%s'"),
3165 diCurrent.strHref.c_str());
3166 }
3167 else
3168 {
3169 ++oit;
3170 }
3171 }
3172 else
3173 {
3174 ++oit;
3175 continue;
3176 }
3177 }
3178 else
3179 {
3180 /* just continue with normal files*/
3181 ++oit;
3182 }
3183
3184 /* very important to store disk name for the next checks */
3185 disksResolvedNames.insert(diCurrent.strHref);
3186////// end of duplicated code.
3187 const ovf::VirtualDisk &ovfVdisk = itVDisk->second;
3188
3189 ComObjPtr<Medium> pTargetHD;
3190
3191 Utf8Str savedVBoxCurrent = vsdeTargetHD->strVBoxCurrent;
3192
3193 i_importOneDiskImage(diCurrent,
3194 &vsdeTargetHD->strVBoxCurrent,
3195 pTargetHD,
3196 stack);
3197
3198 // now use the new uuid to attach the disk image to our new machine
3199 ComPtr<IMachine> sMachine;
3200 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
3201 if (FAILED(rc))
3202 throw rc;
3203
3204 // find the hard disk controller to which we should attach
3205 ovf::HardDiskController hdc = (*vsysThis.mapControllers.find(ovfVdisk.idController)).second;
3206
3207 // this is for rollback later
3208 MyHardDiskAttachment mhda;
3209 mhda.pMachine = pNewMachine;
3210
3211 i_convertDiskAttachmentValues(hdc,
3212 ovfVdisk.ulAddressOnParent,
3213 mhda.controllerType, // Bstr
3214 mhda.lControllerPort,
3215 mhda.lDevice);
3216
3217 Log(("Attaching disk %s to port %d on device %d\n",
3218 vsdeTargetHD->strVBoxCurrent.c_str(), mhda.lControllerPort, mhda.lDevice));
3219
3220 ComObjPtr<MediumFormat> mediumFormat;
3221 rc = i_findMediumFormatFromDiskImage(diCurrent, mediumFormat);
3222 if (FAILED(rc))
3223 throw rc;
3224
3225 Bstr bstrFormatName;
3226 rc = mediumFormat->COMGETTER(Name)(bstrFormatName.asOutParam());
3227 if (FAILED(rc))
3228 throw rc;
3229
3230 Utf8Str vdf = Utf8Str(bstrFormatName);
3231
3232 if (vdf.compare("RAW", Utf8Str::CaseInsensitive) == 0)
3233 {
3234 ComPtr<IMedium> dvdImage(pTargetHD);
3235
3236 rc = mVirtualBox->OpenMedium(Bstr(vsdeTargetHD->strVBoxCurrent).raw(),
3237 DeviceType_DVD,
3238 AccessMode_ReadWrite,
3239 false,
3240 dvdImage.asOutParam());
3241
3242 if (FAILED(rc))
3243 throw rc;
3244
3245 rc = sMachine->AttachDevice(mhda.controllerType.raw(),// wstring name
3246 mhda.lControllerPort, // long controllerPort
3247 mhda.lDevice, // long device
3248 DeviceType_DVD, // DeviceType_T type
3249 dvdImage);
3250 if (FAILED(rc))
3251 throw rc;
3252 }
3253 else
3254 {
3255 rc = sMachine->AttachDevice(mhda.controllerType.raw(),// wstring name
3256 mhda.lControllerPort, // long controllerPort
3257 mhda.lDevice, // long device
3258 DeviceType_HardDisk, // DeviceType_T type
3259 pTargetHD);
3260
3261 if (FAILED(rc))
3262 throw rc;
3263 }
3264
3265 stack.llHardDiskAttachments.push_back(mhda);
3266
3267 rc = sMachine->SaveSettings();
3268 if (FAILED(rc))
3269 throw rc;
3270
3271 /* restore */
3272 vsdeTargetHD->strVBoxCurrent = savedVBoxCurrent;
3273
3274 ++cImportedDisks;
3275
3276 } // end while(oit != stack.mapDisks.end())
3277
3278 /*
3279 * quantity of the imported disks isn't equal to the size of the avsdeHDs list.
3280 */
3281 if(cImportedDisks < avsdeHDs.size())
3282 {
3283 Log1Warning(("Not all disk images were imported for VM %s. Check OVF description file.",
3284 vmNameEntry->strOvf.c_str()));
3285 }
3286
3287 // only now that we're done with all disks, close the session
3288 rc = stack.pSession->UnlockMachine();
3289 if (FAILED(rc))
3290 throw rc;
3291 stack.fSessionOpen = false;
3292 }
3293 catch(HRESULT aRC)
3294 {
3295 com::ErrorInfo info;
3296 if (stack.fSessionOpen)
3297 stack.pSession->UnlockMachine();
3298
3299 if (info.isFullAvailable())
3300 throw setError(aRC, Utf8Str(info.getText()).c_str());
3301 else
3302 throw setError(aRC, "Unknown error during OVF import");
3303 }
3304 }
3305 LogFlowFuncLeave();
3306}
3307
3308/**
3309 * Imports one OVF virtual system (described by a vbox:Machine tag represented by the given config
3310 * structure) into VirtualBox by creating an IMachine instance, which is returned.
3311 *
3312 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
3313 * up any leftovers from this function. For this, the given ImportStack instance has received information
3314 * about what needs cleaning up (to support rollback).
3315 *
3316 * The machine config stored in the settings::MachineConfigFile structure contains the UUIDs of
3317 * the disk attachments used by the machine when it was exported. We also add vbox:uuid attributes
3318 * to the OVF disks sections so we can look them up. While importing these UUIDs into a second host
3319 * will most probably work, reimporting them into the same host will cause conflicts, so we always
3320 * generate new ones on import. This involves the following:
3321 *
3322 * 1) Scan the machine config for disk attachments.
3323 *
3324 * 2) For each disk attachment found, look up the OVF disk image from the disk references section
3325 * and import the disk into VirtualBox, which creates a new UUID for it. In the machine config,
3326 * replace the old UUID with the new one.
3327 *
3328 * 3) Change the machine config according to the OVF virtual system descriptions, in case the
3329 * caller has modified them using setFinalValues().
3330 *
3331 * 4) Create the VirtualBox machine with the modfified machine config.
3332 *
3333 * @param config
3334 * @param pNewMachine
3335 * @param stack
3336 */
3337void Appliance::i_importVBoxMachine(ComObjPtr<VirtualSystemDescription> &vsdescThis,
3338 ComPtr<IMachine> &pReturnNewMachine,
3339 ImportStack &stack)
3340{
3341 LogFlowFuncEnter();
3342 Assert(vsdescThis->m->pConfig);
3343
3344 HRESULT rc = S_OK;
3345
3346 settings::MachineConfigFile &config = *vsdescThis->m->pConfig;
3347
3348 /*
3349 * step 1): modify machine config according to OVF config, in case the user
3350 * has modified them using setFinalValues()
3351 */
3352
3353 /* OS Type */
3354 config.machineUserData.strOsType = stack.strOsTypeVBox;
3355 /* Description */
3356 config.machineUserData.strDescription = stack.strDescription;
3357 /* CPU count & extented attributes */
3358 config.hardwareMachine.cCPUs = stack.cCPUs;
3359 if (stack.fForceIOAPIC)
3360 config.hardwareMachine.fHardwareVirt = true;
3361 if (stack.fForceIOAPIC)
3362 config.hardwareMachine.biosSettings.fIOAPICEnabled = true;
3363 /* RAM size */
3364 config.hardwareMachine.ulMemorySizeMB = stack.ulMemorySizeMB;
3365
3366/*
3367 <const name="HardDiskControllerIDE" value="14" />
3368 <const name="HardDiskControllerSATA" value="15" />
3369 <const name="HardDiskControllerSCSI" value="16" />
3370 <const name="HardDiskControllerSAS" value="17" />
3371*/
3372
3373#ifdef VBOX_WITH_USB
3374 /* USB controller */
3375 if (stack.fUSBEnabled)
3376 {
3377 /** @todo r=klaus add support for arbitrary USB controller types, this can't handle
3378 * multiple controllers due to its design anyway */
3379 /* usually the OHCI controller is enabled already, need to check */
3380 bool fOHCIEnabled = false;
3381 settings::USBControllerList &llUSBControllers = config.hardwareMachine.usbSettings.llUSBControllers;
3382 settings::USBControllerList::iterator it;
3383 for (it = llUSBControllers.begin(); it != llUSBControllers.end(); ++it)
3384 {
3385 if (it->enmType == USBControllerType_OHCI)
3386 {
3387 fOHCIEnabled = true;
3388 break;
3389 }
3390 }
3391
3392 if (!fOHCIEnabled)
3393 {
3394 settings::USBController ctrl;
3395 ctrl.strName = "OHCI";
3396 ctrl.enmType = USBControllerType_OHCI;
3397
3398 llUSBControllers.push_back(ctrl);
3399 }
3400 }
3401 else
3402 config.hardwareMachine.usbSettings.llUSBControllers.clear();
3403#endif
3404 /* Audio adapter */
3405 if (stack.strAudioAdapter.isNotEmpty())
3406 {
3407 config.hardwareMachine.audioAdapter.fEnabled = true;
3408 config.hardwareMachine.audioAdapter.controllerType = (AudioControllerType_T)stack.strAudioAdapter.toUInt32();
3409 }
3410 else
3411 config.hardwareMachine.audioAdapter.fEnabled = false;
3412 /* Network adapter */
3413 settings::NetworkAdaptersList &llNetworkAdapters = config.hardwareMachine.llNetworkAdapters;
3414 /* First disable all network cards, they will be enabled below again. */
3415 settings::NetworkAdaptersList::iterator it1;
3416 bool fKeepAllMACs = m->optListImport.contains(ImportOptions_KeepAllMACs);
3417 bool fKeepNATMACs = m->optListImport.contains(ImportOptions_KeepNATMACs);
3418 for (it1 = llNetworkAdapters.begin(); it1 != llNetworkAdapters.end(); ++it1)
3419 {
3420 it1->fEnabled = false;
3421 if (!( fKeepAllMACs
3422 || (fKeepNATMACs && it1->mode == NetworkAttachmentType_NAT)
3423 || (fKeepNATMACs && it1->mode == NetworkAttachmentType_NATNetwork)))
3424 Host::i_generateMACAddress(it1->strMACAddress);
3425 }
3426 /* Now iterate over all network entries. */
3427 std::list<VirtualSystemDescriptionEntry*> avsdeNWs = vsdescThis->i_findByType(VirtualSystemDescriptionType_NetworkAdapter);
3428 if (!avsdeNWs.empty())
3429 {
3430 /* Iterate through all network adapter entries and search for the
3431 * corresponding one in the machine config. If one is found, configure
3432 * it based on the user settings. */
3433 list<VirtualSystemDescriptionEntry*>::const_iterator itNW;
3434 for (itNW = avsdeNWs.begin();
3435 itNW != avsdeNWs.end();
3436 ++itNW)
3437 {
3438 VirtualSystemDescriptionEntry *vsdeNW = *itNW;
3439 if ( vsdeNW->strExtraConfigCurrent.startsWith("slot=", Utf8Str::CaseInsensitive)
3440 && vsdeNW->strExtraConfigCurrent.length() > 6)
3441 {
3442 uint32_t iSlot = vsdeNW->strExtraConfigCurrent.substr(5, 1).toUInt32();
3443 /* Iterate through all network adapters in the machine config. */
3444 for (it1 = llNetworkAdapters.begin();
3445 it1 != llNetworkAdapters.end();
3446 ++it1)
3447 {
3448 /* Compare the slots. */
3449 if (it1->ulSlot == iSlot)
3450 {
3451 it1->fEnabled = true;
3452 it1->type = (NetworkAdapterType_T)vsdeNW->strVBoxCurrent.toUInt32();
3453 break;
3454 }
3455 }
3456 }
3457 }
3458 }
3459
3460 /* Floppy controller */
3461 bool fFloppy = vsdescThis->i_findByType(VirtualSystemDescriptionType_Floppy).size() > 0;
3462 /* DVD controller */
3463 bool fDVD = vsdescThis->i_findByType(VirtualSystemDescriptionType_CDROM).size() > 0;
3464 /* Iterate over all storage controller check the attachments and remove
3465 * them when necessary. Also detect broken configs with more than one
3466 * attachment. Old VirtualBox versions (prior to 3.2.10) had all disk
3467 * attachments pointing to the last hard disk image, which causes import
3468 * failures. A long fixed bug, however the OVF files are long lived. */
3469 settings::StorageControllersList &llControllers = config.storageMachine.llStorageControllers;
3470 Guid hdUuid;
3471 uint32_t cDisks = 0;
3472 bool fInconsistent = false;
3473 bool fRepairDuplicate = false;
3474 settings::StorageControllersList::iterator it3;
3475 for (it3 = llControllers.begin();
3476 it3 != llControllers.end();
3477 ++it3)
3478 {
3479 settings::AttachedDevicesList &llAttachments = it3->llAttachedDevices;
3480 settings::AttachedDevicesList::iterator it4 = llAttachments.begin();
3481 while (it4 != llAttachments.end())
3482 {
3483 if ( ( !fDVD
3484 && it4->deviceType == DeviceType_DVD)
3485 ||
3486 ( !fFloppy
3487 && it4->deviceType == DeviceType_Floppy))
3488 {
3489 it4 = llAttachments.erase(it4);
3490 continue;
3491 }
3492 else if (it4->deviceType == DeviceType_HardDisk)
3493 {
3494 const Guid &thisUuid = it4->uuid;
3495 cDisks++;
3496 if (cDisks == 1)
3497 {
3498 if (hdUuid.isZero())
3499 hdUuid = thisUuid;
3500 else
3501 fInconsistent = true;
3502 }
3503 else
3504 {
3505 if (thisUuid.isZero())
3506 fInconsistent = true;
3507 else if (thisUuid == hdUuid)
3508 fRepairDuplicate = true;
3509 }
3510 }
3511 ++it4;
3512 }
3513 }
3514 /* paranoia... */
3515 if (fInconsistent || cDisks == 1)
3516 fRepairDuplicate = false;
3517
3518 /*
3519 * step 2: scan the machine config for media attachments
3520 */
3521 /* get VM name from virtual system description. Only one record is possible (size of list is equal 1). */
3522 std::list<VirtualSystemDescriptionEntry*> vmName = vsdescThis->i_findByType(VirtualSystemDescriptionType_Name);
3523 std::list<VirtualSystemDescriptionEntry*>::iterator vmNameIt = vmName.begin();
3524 VirtualSystemDescriptionEntry* vmNameEntry = *vmNameIt;
3525
3526 /* Get all hard disk descriptions. */
3527 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskImage);
3528 std::list<VirtualSystemDescriptionEntry*>::iterator avsdeHDsIt = avsdeHDs.begin();
3529 /* paranoia - if there is no 1:1 match do not try to repair. */
3530 if (cDisks != avsdeHDs.size())
3531 fRepairDuplicate = false;
3532
3533 // there must be an image in the OVF disk structs with the same UUID
3534
3535 ovf::DiskImagesMap::const_iterator oit = stack.mapDisks.begin();
3536 std::set<RTCString> disksResolvedNames;
3537
3538 uint32_t cImportedDisks = 0;
3539
3540 while (oit != stack.mapDisks.end() && cImportedDisks != avsdeHDs.size())
3541 {
3542/** @todo r=bird: Most of the code here is duplicated in the other machine
3543 * import method, factor out. */
3544 ovf::DiskImage diCurrent = oit->second;
3545
3546 Log(("diCurrent.strDiskId=%s diCurrent.strHref=%s\n", diCurrent.strDiskId.c_str(), diCurrent.strHref.c_str()));
3547
3548 /* Iterate over all given disk images of the virtual system
3549 * disks description. We need to find the target disk path,
3550 * which could be changed by the user. */
3551 VirtualSystemDescriptionEntry *vsdeTargetHD = NULL;
3552 for (list<VirtualSystemDescriptionEntry*>::const_iterator itHD = avsdeHDs.begin();
3553 itHD != avsdeHDs.end();
3554 ++itHD)
3555 {
3556 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
3557 if (vsdeHD->strRef == oit->first)
3558 {
3559 vsdeTargetHD = vsdeHD;
3560 break;
3561 }
3562 }
3563 if (!vsdeTargetHD)
3564 {
3565 /* possible case if a disk image belongs to other virtual system (OVF package with multiple VMs inside) */
3566 Log1Warning(("OVA/OVF import: Disk image %s was missed during import of VM %s\n",
3567 oit->first.c_str(), vmNameEntry->strOvf.c_str()));
3568 NOREF(vmNameEntry);
3569 ++oit;
3570 continue;
3571 }
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581 /*
3582 * preliminary check availability of the image
3583 * This step is useful if image is placed in the OVA (TAR) package
3584 */
3585 if (stack.hVfsFssOva != NIL_RTVFSFSSTREAM)
3586 {
3587 /* It means that we possibly have imported the storage earlier on a previous loop step. */
3588 std::set<RTCString>::const_iterator h = disksResolvedNames.find(diCurrent.strHref);
3589 if (h != disksResolvedNames.end())
3590 {
3591 /* Yes, disk name was found, we can skip it*/
3592 ++oit;
3593 continue;
3594 }
3595l_skipped:
3596 rc = i_preCheckImageAvailability(stack);
3597 if (SUCCEEDED(rc))
3598 {
3599 /* current opened file isn't the same as passed one */
3600 if (RTStrICmp(diCurrent.strHref.c_str(), stack.pszOvaLookAheadName) != 0)
3601 {
3602 // availableImage contains the disk identifier (e.g. "vmdisk1"), which should exist
3603 // in the virtual system's disks map under that ID and also in the global images map
3604 // and find the disk from the OVF's disk list
3605 ovf::DiskImagesMap::const_iterator itDiskImage;
3606 for (itDiskImage = stack.mapDisks.begin();
3607 itDiskImage != stack.mapDisks.end();
3608 itDiskImage++)
3609 if (itDiskImage->second.strHref.compare(stack.pszOvaLookAheadName,
3610 Utf8Str::CaseInsensitive) == 0)
3611 break;
3612 if (itDiskImage == stack.mapDisks.end())
3613 {
3614 LogFunc(("Skipping '%s'\n", stack.pszOvaLookAheadName));
3615 RTVfsIoStrmRelease(stack.claimOvaLookAHead());
3616 goto l_skipped;
3617 }
3618 //throw setError(E_FAIL,
3619 // tr("Internal inconsistency looking up disk image '%s'. "
3620 // "Check compliance OVA package structure and file names "
3621 // "references in the section <References> in the OVF file."),
3622 // stack.pszOvaLookAheadName);
3623
3624 /* replace with a new found disk image */
3625 diCurrent = *(&itDiskImage->second);
3626
3627 /*
3628 * Again iterate over all given disk images of the virtual system
3629 * disks description using the found disk image
3630 */
3631 for (list<VirtualSystemDescriptionEntry*>::const_iterator itHD = avsdeHDs.begin();
3632 itHD != avsdeHDs.end();
3633 ++itHD)
3634 {
3635 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
3636 if (vsdeHD->strRef == diCurrent.strDiskId)
3637 {
3638 vsdeTargetHD = vsdeHD;
3639 break;
3640 }
3641 }
3642
3643 /*
3644 * in this case it's an error because something is wrong with the OVF description file.
3645 * May be VBox imports OVA package with wrong file sequence inside the archive.
3646 */
3647 if (!vsdeTargetHD)
3648 throw setError(E_FAIL,
3649 tr("Internal inconsistency looking up disk image '%s'"),
3650 diCurrent.strHref.c_str());
3651
3652
3653
3654
3655
3656 }
3657 else
3658 {
3659 ++oit;
3660 }
3661 }
3662 else
3663 {
3664 ++oit;
3665 continue;
3666 }
3667 }
3668 else
3669 {
3670 /* just continue with normal files*/
3671 ++oit;
3672 }
3673
3674 /* Important! to store disk name for the next checks */
3675 disksResolvedNames.insert(diCurrent.strHref);
3676////// end of duplicated code.
3677 // there must be an image in the OVF disk structs with the same UUID
3678 bool fFound = false;
3679 Utf8Str strUuid;
3680
3681 // for each storage controller...
3682 for (settings::StorageControllersList::iterator sit = config.storageMachine.llStorageControllers.begin();
3683 sit != config.storageMachine.llStorageControllers.end();
3684 ++sit)
3685 {
3686 settings::StorageController &sc = *sit;
3687
3688 // find the OVF virtual system description entry for this storage controller
3689 switch (sc.storageBus)
3690 {
3691 case StorageBus_SATA:
3692 break;
3693 case StorageBus_SCSI:
3694 break;
3695 case StorageBus_IDE:
3696 break;
3697 case StorageBus_SAS:
3698 break;
3699 }
3700
3701 // for each medium attachment to this controller...
3702 for (settings::AttachedDevicesList::iterator dit = sc.llAttachedDevices.begin();
3703 dit != sc.llAttachedDevices.end();
3704 ++dit)
3705 {
3706 settings::AttachedDevice &d = *dit;
3707
3708 if (d.uuid.isZero())
3709 // empty DVD and floppy media
3710 continue;
3711
3712 // When repairing a broken VirtualBox xml config section (written
3713 // by VirtualBox versions earlier than 3.2.10) assume the disks
3714 // show up in the same order as in the OVF description.
3715 if (fRepairDuplicate)
3716 {
3717 VirtualSystemDescriptionEntry *vsdeHD = *avsdeHDsIt;
3718 ovf::DiskImagesMap::const_iterator itDiskImage = stack.mapDisks.find(vsdeHD->strRef);
3719 if (itDiskImage != stack.mapDisks.end())
3720 {
3721 const ovf::DiskImage &di = itDiskImage->second;
3722 d.uuid = Guid(di.uuidVBox);
3723 }
3724 ++avsdeHDsIt;
3725 }
3726
3727 // convert the Guid to string
3728 strUuid = d.uuid.toString();
3729
3730 if (diCurrent.uuidVBox != strUuid)
3731 {
3732 continue;
3733 }
3734
3735 /*
3736 * step 3: import disk
3737 */
3738 Utf8Str savedVBoxCurrent = vsdeTargetHD->strVBoxCurrent;
3739 ComObjPtr<Medium> pTargetHD;
3740
3741 i_importOneDiskImage(diCurrent,
3742 &vsdeTargetHD->strVBoxCurrent,
3743 pTargetHD,
3744 stack);
3745
3746 Bstr hdId;
3747
3748 ComObjPtr<MediumFormat> mediumFormat;
3749 rc = i_findMediumFormatFromDiskImage(diCurrent, mediumFormat);
3750 if (FAILED(rc))
3751 throw rc;
3752
3753 Bstr bstrFormatName;
3754 rc = mediumFormat->COMGETTER(Name)(bstrFormatName.asOutParam());
3755 if (FAILED(rc))
3756 throw rc;
3757
3758 Utf8Str vdf = Utf8Str(bstrFormatName);
3759
3760 if (vdf.compare("RAW", Utf8Str::CaseInsensitive) == 0)
3761 {
3762 ComPtr<IMedium> dvdImage(pTargetHD);
3763
3764 rc = mVirtualBox->OpenMedium(Bstr(vsdeTargetHD->strVBoxCurrent).raw(),
3765 DeviceType_DVD,
3766 AccessMode_ReadWrite,
3767 false,
3768 dvdImage.asOutParam());
3769
3770 if (FAILED(rc)) throw rc;
3771
3772 // ... and replace the old UUID in the machine config with the one of
3773 // the imported disk that was just created
3774 rc = dvdImage->COMGETTER(Id)(hdId.asOutParam());
3775 if (FAILED(rc)) throw rc;
3776 }
3777 else
3778 {
3779 // ... and replace the old UUID in the machine config with the one of
3780 // the imported disk that was just created
3781 rc = pTargetHD->COMGETTER(Id)(hdId.asOutParam());
3782 if (FAILED(rc)) throw rc;
3783 }
3784
3785 /* restore */
3786 vsdeTargetHD->strVBoxCurrent = savedVBoxCurrent;
3787
3788 /*
3789 * 1. saving original UUID for restoring in case of failure.
3790 * 2. replacement of original UUID by new UUID in the current VM config (settings::MachineConfigFile).
3791 */
3792 {
3793 rc = stack.saveOriginalUUIDOfAttachedDevice(d, Utf8Str(hdId));
3794 d.uuid = hdId;
3795 }
3796
3797 fFound = true;
3798 break;
3799 } // for (settings::AttachedDevicesList::const_iterator dit = sc.llAttachedDevices.begin();
3800 } // for (settings::StorageControllersList::const_iterator sit = config.storageMachine.llStorageControllers.begin();
3801
3802 // no disk with such a UUID found:
3803 if (!fFound)
3804 throw setError(E_FAIL,
3805 tr("<vbox:Machine> element in OVF contains a medium attachment for the disk image %s "
3806 "but the OVF describes no such image"),
3807 strUuid.c_str());
3808
3809 ++cImportedDisks;
3810
3811 }// while(oit != stack.mapDisks.end())
3812
3813
3814 /*
3815 * quantity of the imported disks isn't equal to the size of the avsdeHDs list.
3816 */
3817 if(cImportedDisks < avsdeHDs.size())
3818 {
3819 Log1Warning(("Not all disk images were imported for VM %s. Check OVF description file.",
3820 vmNameEntry->strOvf.c_str()));
3821 }
3822
3823 /*
3824 * step 4): create the machine and have it import the config
3825 */
3826
3827 ComObjPtr<Machine> pNewMachine;
3828 rc = pNewMachine.createObject();
3829 if (FAILED(rc)) throw rc;
3830
3831 // this magic constructor fills the new machine object with the MachineConfig
3832 // instance that we created from the vbox:Machine
3833 rc = pNewMachine->init(mVirtualBox,
3834 stack.strNameVBox,// name from OVF preparations; can be suffixed to avoid duplicates
3835 config); // the whole machine config
3836 if (FAILED(rc)) throw rc;
3837
3838 pReturnNewMachine = ComPtr<IMachine>(pNewMachine);
3839
3840 // and register it
3841 rc = mVirtualBox->RegisterMachine(pNewMachine);
3842 if (FAILED(rc)) throw rc;
3843
3844 // store new machine for roll-back in case of errors
3845 Bstr bstrNewMachineId;
3846 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
3847 if (FAILED(rc)) throw rc;
3848 m->llGuidsMachinesCreated.push_back(Guid(bstrNewMachineId));
3849
3850 LogFlowFuncLeave();
3851}
3852
3853/**
3854 * @throws HRESULT errors.
3855 */
3856void Appliance::i_importMachines(ImportStack &stack)
3857{
3858 // this is safe to access because this thread only gets started
3859 const ovf::OVFReader &reader = *m->pReader;
3860
3861 // create a session for the machine + disks we manipulate below
3862 HRESULT rc = stack.pSession.createInprocObject(CLSID_Session);
3863 ComAssertComRCThrowRC(rc);
3864
3865 list<ovf::VirtualSystem>::const_iterator it;
3866 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it1;
3867 /* Iterate through all virtual systems of that appliance */
3868 size_t i = 0;
3869 for (it = reader.m_llVirtualSystems.begin(), it1 = m->virtualSystemDescriptions.begin();
3870 it != reader.m_llVirtualSystems.end() && it1 != m->virtualSystemDescriptions.end();
3871 ++it, ++it1, ++i)
3872 {
3873 const ovf::VirtualSystem &vsysThis = *it;
3874 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it1);
3875
3876 ComPtr<IMachine> pNewMachine;
3877
3878 // there are two ways in which we can create a vbox machine from OVF:
3879 // -- either this OVF was written by vbox 3.2 or later, in which case there is a <vbox:Machine> element
3880 // in the <VirtualSystem>; then the VirtualSystemDescription::Data has a settings::MachineConfigFile
3881 // with all the machine config pretty-parsed;
3882 // -- or this is an OVF from an older vbox or an external source, and then we need to translate the
3883 // VirtualSystemDescriptionEntry and do import work
3884
3885 // Even for the vbox:Machine case, there are a number of configuration items that will be taken from
3886 // the OVF because otherwise the "override import parameters" mechanism in the GUI won't work.
3887
3888 // VM name
3889 std::list<VirtualSystemDescriptionEntry*> vsdeName = vsdescThis->i_findByType(VirtualSystemDescriptionType_Name);
3890 if (vsdeName.size() < 1)
3891 throw setError(VBOX_E_FILE_ERROR,
3892 tr("Missing VM name"));
3893 stack.strNameVBox = vsdeName.front()->strVBoxCurrent;
3894
3895 // have VirtualBox suggest where the filename would be placed so we can
3896 // put the disk images in the same directory
3897 Bstr bstrMachineFilename;
3898 rc = mVirtualBox->ComposeMachineFilename(Bstr(stack.strNameVBox).raw(),
3899 NULL /* aGroup */,
3900 NULL /* aCreateFlags */,
3901 NULL /* aBaseFolder */,
3902 bstrMachineFilename.asOutParam());
3903 if (FAILED(rc)) throw rc;
3904 // and determine the machine folder from that
3905 stack.strMachineFolder = bstrMachineFilename;
3906 stack.strMachineFolder.stripFilename();
3907 LogFunc(("i=%zu strName=%s bstrMachineFilename=%ls\n", i, stack.strNameVBox.c_str(), bstrMachineFilename.raw()));
3908
3909 // guest OS type
3910 std::list<VirtualSystemDescriptionEntry*> vsdeOS;
3911 vsdeOS = vsdescThis->i_findByType(VirtualSystemDescriptionType_OS);
3912 if (vsdeOS.size() < 1)
3913 throw setError(VBOX_E_FILE_ERROR,
3914 tr("Missing guest OS type"));
3915 stack.strOsTypeVBox = vsdeOS.front()->strVBoxCurrent;
3916
3917 // CPU count
3918 std::list<VirtualSystemDescriptionEntry*> vsdeCPU = vsdescThis->i_findByType(VirtualSystemDescriptionType_CPU);
3919 if (vsdeCPU.size() != 1)
3920 throw setError(VBOX_E_FILE_ERROR, tr("CPU count missing"));
3921
3922 stack.cCPUs = vsdeCPU.front()->strVBoxCurrent.toUInt32();
3923 // We need HWVirt & IO-APIC if more than one CPU is requested
3924 if (stack.cCPUs > 1)
3925 {
3926 stack.fForceHWVirt = true;
3927 stack.fForceIOAPIC = true;
3928 }
3929
3930 // RAM
3931 std::list<VirtualSystemDescriptionEntry*> vsdeRAM = vsdescThis->i_findByType(VirtualSystemDescriptionType_Memory);
3932 if (vsdeRAM.size() != 1)
3933 throw setError(VBOX_E_FILE_ERROR, tr("RAM size missing"));
3934 stack.ulMemorySizeMB = (ULONG)vsdeRAM.front()->strVBoxCurrent.toUInt64();
3935
3936#ifdef VBOX_WITH_USB
3937 // USB controller
3938 std::list<VirtualSystemDescriptionEntry*> vsdeUSBController =
3939 vsdescThis->i_findByType(VirtualSystemDescriptionType_USBController);
3940 // USB support is enabled if there's at least one such entry; to disable USB support,
3941 // the type of the USB item would have been changed to "ignore"
3942 stack.fUSBEnabled = !vsdeUSBController.empty();
3943#endif
3944 // audio adapter
3945 std::list<VirtualSystemDescriptionEntry*> vsdeAudioAdapter =
3946 vsdescThis->i_findByType(VirtualSystemDescriptionType_SoundCard);
3947 /* @todo: we support one audio adapter only */
3948 if (!vsdeAudioAdapter.empty())
3949 stack.strAudioAdapter = vsdeAudioAdapter.front()->strVBoxCurrent;
3950
3951 // for the description of the new machine, always use the OVF entry, the user may have changed it in the import config
3952 std::list<VirtualSystemDescriptionEntry*> vsdeDescription =
3953 vsdescThis->i_findByType(VirtualSystemDescriptionType_Description);
3954 if (!vsdeDescription.empty())
3955 stack.strDescription = vsdeDescription.front()->strVBoxCurrent;
3956
3957 // import vbox:machine or OVF now
3958 if (vsdescThis->m->pConfig)
3959 // vbox:Machine config
3960 i_importVBoxMachine(vsdescThis, pNewMachine, stack);
3961 else
3962 // generic OVF config
3963 i_importMachineGeneric(vsysThis, vsdescThis, pNewMachine, stack);
3964
3965 } // for (it = pAppliance->m->llVirtualSystems.begin() ...
3966}
3967
3968HRESULT Appliance::ImportStack::saveOriginalUUIDOfAttachedDevice(settings::AttachedDevice &device,
3969 const Utf8Str &newlyUuid)
3970{
3971 HRESULT rc = S_OK;
3972
3973 /* save for restoring */
3974 mapNewUUIDsToOriginalUUIDs.insert(std::make_pair(newlyUuid, device.uuid.toString()));
3975
3976 return rc;
3977}
3978
3979HRESULT Appliance::ImportStack::restoreOriginalUUIDOfAttachedDevice(settings::MachineConfigFile *config)
3980{
3981 HRESULT rc = S_OK;
3982
3983 settings::StorageControllersList &llControllers = config->storageMachine.llStorageControllers;
3984 settings::StorageControllersList::iterator itscl;
3985 for (itscl = llControllers.begin();
3986 itscl != llControllers.end();
3987 ++itscl)
3988 {
3989 settings::AttachedDevicesList &llAttachments = itscl->llAttachedDevices;
3990 settings::AttachedDevicesList::iterator itadl = llAttachments.begin();
3991 while (itadl != llAttachments.end())
3992 {
3993 std::map<Utf8Str , Utf8Str>::iterator it =
3994 mapNewUUIDsToOriginalUUIDs.find(itadl->uuid.toString());
3995 if(it!=mapNewUUIDsToOriginalUUIDs.end())
3996 {
3997 Utf8Str uuidOriginal = it->second;
3998 itadl->uuid = Guid(uuidOriginal);
3999 mapNewUUIDsToOriginalUUIDs.erase(it->first);
4000 }
4001 ++itadl;
4002 }
4003 }
4004
4005 return rc;
4006}
4007
4008/**
4009 * @throws Nothing
4010 */
4011RTVFSIOSTREAM Appliance::ImportStack::claimOvaLookAHead(void)
4012{
4013 RTVFSIOSTREAM hVfsIos = this->hVfsIosOvaLookAhead;
4014 this->hVfsIosOvaLookAhead = NIL_RTVFSIOSTREAM;
4015 /* We don't free the name since it may be referenced in error messages and such. */
4016 return hVfsIos;
4017}
4018
Note: See TracBrowser for help on using the repository browser.

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