VirtualBox

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

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

ApplianceImpl: Signature and certificate validation updates.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 171.3 KB
Line 
1/* $Id: ApplianceImplImport.cpp 59679 2016-02-15 13:10:06Z 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 m->fCertificateIsSelfSigned = RTCrX509Certificate_IsSelfSigned(&m->SignerCert);
1573
1574 /*
1575 * Find the start of the certificate part of the file, so we can avoid
1576 * upsetting the manifest parser with it.
1577 */
1578 char *pszSplit = (char *)RTCrPemFindFirstSectionInContent(pvSignature, cbSignature,
1579 g_aRTCrX509CertificateMarkers, g_cRTCrX509CertificateMarkers);
1580 if (pszSplit)
1581 while ( pszSplit != (char *)pvSignature
1582 && pszSplit[-1] != '\n'
1583 && pszSplit[-1] != '\r')
1584 pszSplit--;
1585 else
1586 {
1587 AssertLogRelMsgFailed(("Failed to find BEGIN CERTIFICATE markers in '%s'::'%s' - impossible unless it's a DER encoded certificate!",
1588 pTask->locInfo.strPath.c_str(), pszSubFileNm));
1589 pszSplit = (char *)pvSignature + cbSignature;
1590 }
1591 *pszSplit = '\0';
1592
1593 /*
1594 * Now, read the manifest part. We use the IPRT manifest reader here
1595 * to avoid duplicating code and be somewhat flexible wrt the digest
1596 * type choosen by the signer.
1597 */
1598 RTMANIFEST hSignedDigestManifest;
1599 vrc = RTManifestCreate(0 /*fFlags*/, &hSignedDigestManifest);
1600 if (RT_SUCCESS(vrc))
1601 {
1602 RTVFSIOSTREAM hVfsIosTmp;
1603 vrc = RTVfsIoStrmFromBuffer(RTFILE_O_READ, pvSignature, pszSplit - (char *)pvSignature, &hVfsIosTmp);
1604 if (RT_SUCCESS(vrc))
1605 {
1606 vrc = RTManifestReadStandardEx(hSignedDigestManifest, hVfsIosTmp, StaticErrInfo.szMsg, sizeof(StaticErrInfo.szMsg));
1607 RTVfsIoStrmRelease(hVfsIosTmp);
1608 if (RT_SUCCESS(vrc))
1609 {
1610 /*
1611 * Get signed digest, we prefer SHA-2, so explicitly query those first.
1612 */
1613 uint32_t fDigestType;
1614 char szSignedDigest[_8K + 1];
1615 vrc = RTManifestEntryQueryAttr(hSignedDigestManifest, strManifestName.c_str(), NULL,
1616 RTMANIFEST_ATTR_SHA512 | RTMANIFEST_ATTR_SHA256,
1617 szSignedDigest, sizeof(szSignedDigest), &fDigestType);
1618 if (vrc == VERR_MANIFEST_ATTR_TYPE_NOT_FOUND)
1619 vrc = RTManifestEntryQueryAttr(hSignedDigestManifest, strManifestName.c_str(), NULL,
1620 RTMANIFEST_ATTR_ANY, szSignedDigest, sizeof(szSignedDigest), &fDigestType);
1621 if (RT_SUCCESS(vrc))
1622 {
1623 const char *pszSignedDigest = RTStrStrip(szSignedDigest);
1624 size_t cbSignedDigest = strlen(pszSignedDigest) / 2;
1625 uint8_t abSignedDigest[sizeof(szSignedDigest) / 2];
1626 vrc = RTStrConvertHexBytes(szSignedDigest, abSignedDigest, cbSignedDigest, 0 /*fFlags*/);
1627 if (RT_SUCCESS(vrc))
1628 {
1629 /*
1630 * Convert it to RTDIGESTTYPE_XXX and save the binary value for later use.
1631 */
1632 switch (fDigestType)
1633 {
1634 case RTMANIFEST_ATTR_SHA1: m->enmSignedDigestType = RTDIGESTTYPE_SHA1; break;
1635 case RTMANIFEST_ATTR_SHA256: m->enmSignedDigestType = RTDIGESTTYPE_SHA256; break;
1636 case RTMANIFEST_ATTR_SHA512: m->enmSignedDigestType = RTDIGESTTYPE_SHA512; break;
1637 case RTMANIFEST_ATTR_MD5: m->enmSignedDigestType = RTDIGESTTYPE_MD5; break;
1638 default: AssertFailed(); m->enmSignedDigestType = RTDIGESTTYPE_INVALID; break;
1639 }
1640 if (m->enmSignedDigestType != RTDIGESTTYPE_INVALID)
1641 {
1642 m->pbSignedDigest = (uint8_t *)RTMemDup(abSignedDigest, cbSignedDigest);
1643 m->cbSignedDigest = cbSignedDigest;
1644 hrc = S_OK;
1645 }
1646 else
1647 hrc = setError(E_FAIL, tr("Unsupported signed digest type (%#x)"), fDigestType);
1648 }
1649 else
1650 hrc = setErrorVrc(vrc, tr("Error reading signed manifest digest: %Rrc"), vrc);
1651 }
1652 else if (vrc == VERR_NOT_FOUND)
1653 hrc = setErrorVrc(vrc, tr("Could not locate signed digest for '%s' in the cert-file for '%s'"),
1654 strManifestName.c_str(), pTask->locInfo.strPath.c_str());
1655 else
1656 hrc = setErrorVrc(vrc, tr("RTManifestEntryQueryAttr failed unexpectedly: %Rrc"), vrc);
1657 }
1658 else
1659 hrc = setErrorVrc(vrc, tr("Error parsing the .cert-file for '%s': %s"),
1660 pTask->locInfo.strPath.c_str(), StaticErrInfo.szMsg);
1661 }
1662 else
1663 hrc = E_OUTOFMEMORY;
1664 RTManifestRelease(hSignedDigestManifest);
1665 }
1666 else
1667 hrc = E_OUTOFMEMORY;
1668 }
1669 else
1670 hrc = setErrorVrc(vrc, tr("Error reading the signer's certificate from '%s' for '%s' (%Rrc): %s"),
1671 pszSubFileNm, pTask->locInfo.strPath.c_str(), vrc, StaticErrInfo.Core.pszMsg);
1672
1673 RTVfsIoStrmReadAllFree(pvSignature, cbSignature);
1674 LogFlowFunc(("returns %Rhrc (%Rrc)\n", hrc, vrc));
1675 return hrc;
1676}
1677
1678
1679/**
1680 * Does tail processing after the files have been read in.
1681 *
1682 * @param pTask The read task.
1683 * @returns COM status.
1684 * @throws Nothing!
1685 */
1686HRESULT Appliance::i_readTailProcessing(TaskOVF *pTask)
1687{
1688 /*
1689 * Parse and validate the signature file.
1690 *
1691 * The signature file has two parts, manifest part and a PEM encoded
1692 * certificate. The former contains an entry for the manifest file with a
1693 * digest that is encrypted with the certificate in the latter part.
1694 */
1695 if (m->pbSignedDigest)
1696 {
1697 /* Since we're validating the digest of the manifest, there have to be
1698 a manifest. We cannot allow a the manifest to be missing. */
1699 if (m->hMemFileTheirManifest == NIL_RTVFSFILE)
1700 return setError(VBOX_E_FILE_ERROR, tr("Found .cert-file but no .mf-file for '%s'"), pTask->locInfo.strPath.c_str());
1701
1702 /*
1703 * Validate the signed digest.
1704 *
1705 * It's possible we should allow the user to ignore signature
1706 * mismatches, but for now it's a show stopper.
1707 */
1708 HRESULT hrc;
1709
1710 /* Calc the digest of the manifest using the algorithm found above. */
1711 RTCRDIGEST hDigest;
1712 int vrc = RTCrDigestCreateByType(&hDigest, m->enmSignedDigestType);
1713 if (RT_SUCCESS(vrc))
1714 {
1715 vrc = RTCrDigestUpdateFromVfsFile(hDigest, m->hMemFileTheirManifest, true /*fRewindFile*/);
1716 if (RT_SUCCESS(vrc))
1717 {
1718 /** @todo convert to something like RTCrPkixPubKeyVerifySignature! */
1719 /* Verify the signature using the certificate. */
1720 RTCRPKIXSIGNATURE hSignature;
1721 vrc = RTCrPkixSignatureCreateByObjId(&hSignature,
1722 &m->SignerCert.TbsCertificate.SubjectPublicKeyInfo.Algorithm.Algorithm,
1723 false /*fSigning*/,
1724 &m->SignerCert.TbsCertificate.SubjectPublicKeyInfo.SubjectPublicKey,
1725 NULL);
1726 if (RT_SUCCESS(vrc))
1727 {
1728 vrc = RTCrPkixSignatureVerify(hSignature, hDigest, m->pbSignedDigest, m->cbSignedDigest);
1729 if (RT_SUCCESS(vrc))
1730 {
1731 m->fSignatureValid = true;
1732 hrc = S_OK;
1733 }
1734 else if (vrc == VERR_CR_PKIX_SIGNATURE_MISMATCH)
1735 hrc = setErrorVrc(vrc, tr("The manifest signature does not match"));
1736 else
1737 hrc = setErrorVrc(vrc, tr("Error validating the manifest signature (%Rrc)"), vrc);
1738 RTCrPkixSignatureRelease(hSignature);
1739 }
1740 else
1741 hrc = setErrorVrc(vrc, tr("RTCrPkixSignatureCreateByObjId failed: %Rrc"), vrc);
1742 }
1743 else
1744 hrc = setErrorVrc(vrc, tr("RTCrDigestUpdateFromVfsFile failed: %Rrc"), vrc);
1745 RTCrDigestRelease(hDigest);
1746 }
1747 else
1748 hrc = setErrorVrc(vrc, tr("RTCrDigestCreateByType failed: %Rrc"), vrc);
1749
1750 /*
1751 * Validate the certificate.
1752 *
1753 * We don't fail here on if we cannot validate the certificate, we postpone
1754 * that till the import stage, so that we can allow the user to ignore it.
1755 *
1756 * The certificate validity time is deliberately ignored as the OVF
1757 * specification does not include a way of timestamping the signature
1758 * and it would be seriously annoying for users if OVAs expired with
1759 * their certificates. This is of course a security concern, but the
1760 * whole signing of OVFs is currently weirdly trusting (self signed
1761 * certs), so this is the least of our current problems.
1762 */
1763 Assert(!m->fCertificateValid);
1764 Assert(m->fCertificateMissingPath);
1765 Assert(!m->fCertificateValidTime);
1766 Assert(m->strCertError.isEmpty());
1767 Assert(m->fCertificateIsSelfSigned == RTCrX509Certificate_IsSelfSigned(&m->SignerCert));
1768
1769 HRESULT hrc2 = S_OK;
1770 RTERRINFOSTATIC StaticErrInfo;
1771 if (m->fCertificateIsSelfSigned)
1772 {
1773 /*
1774 * It's a self signed certificate. We assume the frontend will
1775 * present this fact to the user and give a choice whether this
1776 * is acceptible. But, first make sure it makes internal sense.
1777 */
1778 m->fCertificateMissingPath = false;
1779 vrc = RTCrX509Certificate_VerifySignatureSelfSigned(&m->SignerCert, RTErrInfoInitStatic(&StaticErrInfo));
1780 if (RT_SUCCESS(vrc))
1781 {
1782 m->fCertificateValid = true;
1783
1784 /* Check whether the certificate is currently valid, just warn if not. */
1785 RTTIMESPEC Now;
1786 if (RTCrX509Validity_IsValidAtTimeSpec(&m->SignerCert.TbsCertificate.Validity, RTTimeNow(&Now)))
1787 m->fCertificateValidTime = true;
1788 else
1789 i_addWarning(tr("Self signed certificate used to sign '%s' is not currently valid"),
1790 pTask->locInfo.strPath.c_str());
1791
1792 /* Just warn if it's not a CA. Self-signed certificates are
1793 hardly trustworthy to start with without the user's consent. */
1794 if ( !m->SignerCert.TbsCertificate.T3.pBasicConstraints
1795 || !m->SignerCert.TbsCertificate.T3.pBasicConstraints->CA.fValue)
1796 i_addWarning(tr("Self signed certificate used to sign '%s' is not marked as certificate authority (CA)"),
1797 pTask->locInfo.strPath.c_str());
1798 }
1799 else
1800 {
1801 try { m->strCertError = Utf8StrFmt(tr("Verification of the self signed certificate failed (%Rrc, %s)"),
1802 vrc, StaticErrInfo.Core.pszMsg); }
1803 catch (...) { AssertFailed(); }
1804 i_addWarning(tr("Verification of the self signed certificate used to sign '%s' failed (%Rrc): %s"),
1805 pTask->locInfo.strPath.c_str(), vrc, StaticErrInfo.Core.pszMsg);
1806 }
1807 }
1808 else
1809 {
1810 /*
1811 * The certificate is not self-signed. Use the system certificate
1812 * stores to try build a path that validates successfully.
1813 */
1814 RTCRX509CERTPATHS hCertPaths;
1815 vrc = RTCrX509CertPathsCreate(&hCertPaths, &m->SignerCert);
1816 if (RT_SUCCESS(vrc))
1817 {
1818 /* Get trusted certificates from the system and add them to the path finding mission. */
1819 RTCRSTORE hTrustedCerts;
1820 vrc = RTCrStoreCreateSnapshotOfUserAndSystemTrustedCAsAndCerts(&hTrustedCerts,
1821 RTErrInfoInitStatic(&StaticErrInfo));
1822 if (RT_SUCCESS(vrc))
1823 {
1824 vrc = RTCrX509CertPathsSetTrustedStore(hCertPaths, hTrustedCerts);
1825 if (RT_FAILURE(vrc))
1826 hrc2 = setError(E_FAIL, tr("RTCrX509CertPathsSetTrustedStore failed (%Rrc)"), vrc);
1827 RTCrStoreRelease(hTrustedCerts);
1828 }
1829 else
1830 hrc2 = setError(E_FAIL,
1831 tr("Failed to query trusted CAs and Certificates from the system and for the current user (%Rrc, %s)"),
1832 vrc, StaticErrInfo.Core.pszMsg);
1833
1834 /* Add untrusted intermediate certificates. */
1835 if (RT_SUCCESS(vrc))
1836 {
1837 /// @todo RTCrX509CertPathsSetUntrustedStore(hCertPaths, hAdditionalCerts);
1838 /// By scanning for additional certificates in the .cert file? It would be
1839 /// convenient to be able to supply intermediate certificates for the user,
1840 /// right? Or would that be unacceptable as it may weaken security?
1841 ///
1842 /// Anyway, we should look for intermediate certificates on the system, at
1843 /// least.
1844 }
1845 if (RT_SUCCESS(vrc))
1846 {
1847 /*
1848 * Do the building and verification of certificate paths.
1849 */
1850 vrc = RTCrX509CertPathsBuild(hCertPaths, RTErrInfoInitStatic(&StaticErrInfo));
1851 if (RT_SUCCESS(vrc))
1852 {
1853 vrc = RTCrX509CertPathsValidateAll(hCertPaths, NULL, RTErrInfoInitStatic(&StaticErrInfo));
1854 if (RT_SUCCESS(vrc))
1855 {
1856 /*
1857 * Mark the certificate as good.
1858 */
1859 /** @todo check the certificate purpose? If so, share with self-signed. */
1860 m->fCertificateValid = true;
1861 m->fCertificateMissingPath = false;
1862
1863 /*
1864 * We add a warning if the certificate path isn't valid at the current
1865 * time. Since the time is only considered during path validation and we
1866 * can repeat the validation process (but not building), it's easy to check.
1867 */
1868 RTTIMESPEC Now;
1869 vrc = RTCrX509CertPathsSetValidTimeSpec(hCertPaths, RTTimeNow(&Now));
1870 if (RT_SUCCESS(vrc))
1871 {
1872 vrc = RTCrX509CertPathsValidateAll(hCertPaths, NULL, RTErrInfoInitStatic(&StaticErrInfo));
1873 if (RT_SUCCESS(vrc))
1874 m->fCertificateValidTime = true;
1875 else
1876 i_addWarning(tr("The certificate used to sign '%s' (or a certificate in the path) is not currently valid (%Rrc)"),
1877 pTask->locInfo.strPath.c_str(), vrc);
1878 }
1879 else
1880 hrc2 = setErrorVrc(vrc, "RTCrX509CertPathsSetValidTimeSpec failed: %Rrc", vrc);
1881 }
1882 else if (vrc == VERR_CR_X509_CPV_NO_TRUSTED_PATHS)
1883 {
1884 m->fCertificateValid = true;
1885 i_addWarning(tr("No trusted certificate paths"));
1886 }
1887 else
1888 hrc2 = setError(E_FAIL, tr("Certificate path validation failed (%Rrc, %s)"),
1889 vrc, StaticErrInfo.Core.pszMsg);
1890 }
1891 else
1892 hrc2 = setError(E_FAIL, tr("Certificate path building failed (%Rrc, %s)"),
1893 vrc, StaticErrInfo.Core.pszMsg);
1894 }
1895 RTCrX509CertPathsRelease(hCertPaths);
1896 }
1897 else
1898 hrc2 = setErrorVrc(vrc, tr("RTCrX509CertPathsCreate failed: %Rrc"), vrc);
1899 }
1900
1901 /* Merge statuses from signature and certificate validation, prefering the signature one. */
1902 if (SUCCEEDED(hrc) && FAILED(hrc2))
1903 hrc = hrc2;
1904 if (FAILED(hrc))
1905 return hrc;
1906 }
1907
1908 /** @todo provide details about the signatory, signature, etc. */
1909
1910 /*
1911 * If there is a manifest, check that the OVF digest matches up (if present).
1912 */
1913
1914 NOREF(pTask);
1915 return S_OK;
1916}
1917
1918
1919
1920/*******************************************************************************
1921 * Import stuff
1922 ******************************************************************************/
1923
1924/**
1925 * Implementation for importing OVF data into VirtualBox. This starts a new thread which will call
1926 * Appliance::taskThreadImportOrExport().
1927 *
1928 * This creates one or more new machines according to the VirtualSystemScription instances created by
1929 * Appliance::Interpret().
1930 *
1931 * This is in a separate private method because it is used from one location:
1932 *
1933 * 1) from the public Appliance::ImportMachines().
1934 *
1935 * @param aLocInfo
1936 * @param aProgress
1937 * @return
1938 */
1939HRESULT Appliance::i_importImpl(const LocationInfo &locInfo,
1940 ComObjPtr<Progress> &progress)
1941{
1942 HRESULT rc = S_OK;
1943
1944 SetUpProgressMode mode;
1945 if (locInfo.storageType == VFSType_File)
1946 mode = ImportFile;
1947 else
1948 mode = ImportS3;
1949
1950 rc = i_setUpProgress(progress,
1951 BstrFmt(tr("Importing appliance '%s'"), locInfo.strPath.c_str()),
1952 mode);
1953 if (FAILED(rc)) throw rc;
1954
1955 /* Initialize our worker task */
1956 TaskOVF* task = NULL;
1957 try
1958 {
1959 task = new TaskOVF(this, TaskOVF::Import, locInfo, progress);
1960 }
1961 catch(...)
1962 {
1963 delete task;
1964 throw rc = setError(VBOX_E_OBJECT_NOT_FOUND,
1965 tr("Could not create TaskOVF object for importing OVF data into VirtualBox"));
1966 }
1967
1968 rc = task->createThread();
1969 if (FAILED(rc)) throw rc;
1970
1971 return rc;
1972}
1973
1974/**
1975 * Actual worker code for importing OVF data into VirtualBox.
1976 *
1977 * This is called from Appliance::taskThreadImportOrExport() and therefore runs
1978 * on the OVF import worker thread. This creates one or more new machines
1979 * according to the VirtualSystemScription instances created by
1980 * Appliance::Interpret().
1981 *
1982 * This runs in two contexts:
1983 *
1984 * 1) in a first worker thread; in that case, Appliance::ImportMachines() called
1985 * Appliance::i_importImpl();
1986 *
1987 * 2) in a second worker thread; in that case, Appliance::ImportMachines()
1988 * called Appliance::i_importImpl(), which called Appliance::i_importFSOVA(),
1989 * which called Appliance::i_importImpl(), which then called this again.
1990 *
1991 * @param pTask The OVF task data.
1992 * @return COM status code.
1993 */
1994HRESULT Appliance::i_importFS(TaskOVF *pTask)
1995{
1996 LogFlowFuncEnter();
1997 LogFlowFunc(("Appliance %p\n", this));
1998
1999 /* Change the appliance state so we can safely leave the lock while doing
2000 * time-consuming disk imports; also the below method calls do all kinds of
2001 * locking which conflicts with the appliance object lock. */
2002 AutoWriteLock writeLock(this COMMA_LOCKVAL_SRC_POS);
2003 /* Check if the appliance is currently busy. */
2004 if (!i_isApplianceIdle())
2005 return E_ACCESSDENIED;
2006 /* Set the internal state to importing. */
2007 m->state = Data::ApplianceImporting;
2008
2009 HRESULT rc = S_OK;
2010
2011 /* Clear the list of imported machines, if any */
2012 m->llGuidsMachinesCreated.clear();
2013
2014 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
2015 rc = i_importFSOVF(pTask, writeLock);
2016 else
2017 rc = i_importFSOVA(pTask, writeLock);
2018 if (FAILED(rc))
2019 {
2020 /* With _whatever_ error we've had, do a complete roll-back of
2021 * machines and disks we've created */
2022 writeLock.release();
2023 ErrorInfoKeeper eik;
2024 for (list<Guid>::iterator itID = m->llGuidsMachinesCreated.begin();
2025 itID != m->llGuidsMachinesCreated.end();
2026 ++itID)
2027 {
2028 Guid guid = *itID;
2029 Bstr bstrGuid = guid.toUtf16();
2030 ComPtr<IMachine> failedMachine;
2031 HRESULT rc2 = mVirtualBox->FindMachine(bstrGuid.raw(), failedMachine.asOutParam());
2032 if (SUCCEEDED(rc2))
2033 {
2034 SafeIfaceArray<IMedium> aMedia;
2035 rc2 = failedMachine->Unregister(CleanupMode_DetachAllReturnHardDisksOnly, ComSafeArrayAsOutParam(aMedia));
2036 ComPtr<IProgress> pProgress2;
2037 rc2 = failedMachine->DeleteConfig(ComSafeArrayAsInParam(aMedia), pProgress2.asOutParam());
2038 pProgress2->WaitForCompletion(-1);
2039 }
2040 }
2041 writeLock.acquire();
2042 }
2043
2044 /* Reset the state so others can call methods again */
2045 m->state = Data::ApplianceIdle;
2046
2047 LogFlowFunc(("rc=%Rhrc\n", rc));
2048 LogFlowFuncLeave();
2049 return rc;
2050}
2051
2052HRESULT Appliance::i_importFSOVF(TaskOVF *pTask, AutoWriteLockBase &rWriteLock)
2053{
2054 return i_importDoIt(pTask, rWriteLock);
2055}
2056
2057HRESULT Appliance::i_importFSOVA(TaskOVF *pTask, AutoWriteLockBase &rWriteLock)
2058{
2059 LogFlowFuncEnter();
2060
2061 /*
2062 * Open the tar file as file stream.
2063 */
2064 RTVFSIOSTREAM hVfsIosOva;
2065 int vrc = RTVfsIoStrmOpenNormal(pTask->locInfo.strPath.c_str(),
2066 RTFILE_O_READ | RTFILE_O_DENY_NONE | RTFILE_O_OPEN, &hVfsIosOva);
2067 if (RT_FAILURE(vrc))
2068 return setErrorVrc(vrc, tr("Error opening the OVA file '%s' (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
2069
2070 RTVFSFSSTREAM hVfsFssOva;
2071 vrc = RTZipTarFsStreamFromIoStream(hVfsIosOva, 0 /*fFlags*/, &hVfsFssOva);
2072 RTVfsIoStrmRelease(hVfsIosOva);
2073 if (RT_FAILURE(vrc))
2074 return setErrorVrc(vrc, tr("Error reading the OVA file '%s' (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
2075
2076 /*
2077 * Join paths with the i_importFSOVF code.
2078 *
2079 * Note! We don't need to skip the OVF, manifest or signature files, as the
2080 * i_importMachineGeneric, i_importVBoxMachine and i_importOpenSourceFile
2081 * code will deal with this (as there could be other files in the OVA
2082 * that we don't process, like 'de-DE-resources.xml' in EXAMPLE 1,
2083 * Appendix D.1, OVF v2.1.0).
2084 */
2085 HRESULT hrc = i_importDoIt(pTask, rWriteLock, hVfsFssOva);
2086
2087 RTVfsFsStrmRelease(hVfsFssOva);
2088
2089 LogFlowFunc(("returns %Rhrc\n", hrc));
2090 return hrc;
2091}
2092
2093/**
2094 * Does the actual importing after the caller has made the source accessible.
2095 *
2096 * @param pTask The import task.
2097 * @param rWriteLock The write lock the caller's caller is holding,
2098 * will be released for some reason.
2099 * @param hVfsFssOva The file system stream if OVA, NIL if not.
2100 * @returns COM status code.
2101 * @throws Nothing.
2102 */
2103HRESULT Appliance::i_importDoIt(TaskOVF *pTask, AutoWriteLockBase &rWriteLock, RTVFSFSSTREAM hVfsFssOva /*= NIL_RTVFSFSSTREAM*/)
2104{
2105 rWriteLock.release();
2106
2107 HRESULT hrc = E_FAIL;
2108 try
2109 {
2110 /*
2111 * Create the import stack for the rollback on errors.
2112 */
2113 ImportStack stack(pTask->locInfo, m->pReader->m_mapDisks, pTask->pProgress, hVfsFssOva);
2114
2115 try
2116 {
2117 /* Do the importing. */
2118 i_importMachines(stack);
2119
2120 /* We should've processed all the files now, so compare. */
2121 hrc = i_verifyManifestFile(stack);
2122 }
2123 catch (HRESULT hrcXcpt)
2124 {
2125 hrc = hrcXcpt;
2126 }
2127 catch (...)
2128 {
2129 AssertFailed();
2130 hrc = E_FAIL;
2131 }
2132 if (FAILED(hrc))
2133 {
2134 /*
2135 * Restoring original UUID from OVF description file.
2136 * During import VBox creates new UUIDs for imported images and
2137 * assigns them to the images. In case of failure we have to restore
2138 * the original UUIDs because those new UUIDs are obsolete now and
2139 * won't be used anymore.
2140 */
2141 ErrorInfoKeeper eik; /* paranoia */
2142 list< ComObjPtr<VirtualSystemDescription> >::const_iterator itvsd;
2143 /* Iterate through all virtual systems of that appliance */
2144 for (itvsd = m->virtualSystemDescriptions.begin();
2145 itvsd != m->virtualSystemDescriptions.end();
2146 ++itvsd)
2147 {
2148 ComObjPtr<VirtualSystemDescription> vsdescThis = (*itvsd);
2149 settings::MachineConfigFile *pConfig = vsdescThis->m->pConfig;
2150 if(vsdescThis->m->pConfig!=NULL)
2151 stack.restoreOriginalUUIDOfAttachedDevice(pConfig);
2152 }
2153 }
2154 }
2155 catch (...)
2156 {
2157 hrc = E_FAIL;
2158 AssertFailed();
2159 }
2160
2161 rWriteLock.acquire();
2162 return hrc;
2163}
2164
2165/**
2166 * Undocumented, you figure it from the name.
2167 *
2168 * @returns Undocumented
2169 * @param stack Undocumented.
2170 */
2171HRESULT Appliance::i_verifyManifestFile(ImportStack &stack)
2172{
2173 LogFlowThisFuncEnter();
2174 HRESULT hrc;
2175 int vrc;
2176
2177 /*
2178 * No manifest is fine, it always matches.
2179 */
2180 if (m->hTheirManifest == NIL_RTMANIFEST)
2181 hrc = S_OK;
2182 else
2183 {
2184 /*
2185 * Hack: If the manifest we just read doesn't have a digest for the OVF, copy
2186 * it from the manifest we got from the caller.
2187 * @bugref{6022#c119}
2188 */
2189 if ( !RTManifestEntryExists(m->hTheirManifest, m->strOvfManifestEntry.c_str())
2190 && RTManifestEntryExists(m->hOurManifest, m->strOvfManifestEntry.c_str()) )
2191 {
2192 uint32_t fType = 0;
2193 char szDigest[512 + 1];
2194 vrc = RTManifestEntryQueryAttr(m->hOurManifest, m->strOvfManifestEntry.c_str(), NULL, RTMANIFEST_ATTR_ANY,
2195 szDigest, sizeof(szDigest), &fType);
2196 if (RT_SUCCESS(vrc))
2197 vrc = RTManifestEntrySetAttr(m->hTheirManifest, m->strOvfManifestEntry.c_str(),
2198 NULL /*pszAttr*/, szDigest, fType);
2199 if (RT_FAILURE(vrc))
2200 return setError(VBOX_E_IPRT_ERROR, tr("Error fudging missing OVF digest in manifest: %Rrc"), vrc);
2201 }
2202
2203 /*
2204 * Compare with the digests we've created while read/processing the import.
2205 *
2206 * We specify the RTMANIFEST_EQUALS_IGN_MISSING_ATTRS to ignore attributes
2207 * (SHA1, SHA256, etc) that are only present in one of the manifests, as long
2208 * as each entry has at least one common attribute that we can check. This
2209 * is important for the OVF in OVAs, for which we generates several digests
2210 * since we don't know which are actually used in the manifest (OVF comes
2211 * first in an OVA, then manifest).
2212 */
2213 char szErr[256];
2214 vrc = RTManifestEqualsEx(m->hTheirManifest, m->hOurManifest, NULL /*papszIgnoreEntries*/,
2215 NULL /*papszIgnoreAttrs*/, RTMANIFEST_EQUALS_IGN_MISSING_ATTRS, szErr, sizeof(szErr));
2216 if (RT_SUCCESS(vrc))
2217 hrc = S_OK;
2218 else
2219 hrc = setErrorVrc(vrc, tr("Digest mismatch (%Rrc): %s"), vrc, szErr);
2220 }
2221
2222 NOREF(stack);
2223 LogFlowThisFunc(("returns %Rhrc\n", hrc));
2224 return hrc;
2225}
2226
2227/**
2228 * Helper that converts VirtualSystem attachment values into VirtualBox attachment values.
2229 * Throws HRESULT values on errors!
2230 *
2231 * @param hdc in: the HardDiskController structure to attach to.
2232 * @param ulAddressOnParent in: the AddressOnParent parameter from OVF.
2233 * @param controllerType out: the name of the hard disk controller to attach to (e.g. "IDE Controller").
2234 * @param lControllerPort out: the channel (controller port) of the controller to attach to.
2235 * @param lDevice out: the device number to attach to.
2236 */
2237void Appliance::i_convertDiskAttachmentValues(const ovf::HardDiskController &hdc,
2238 uint32_t ulAddressOnParent,
2239 Bstr &controllerType,
2240 int32_t &lControllerPort,
2241 int32_t &lDevice)
2242{
2243 Log(("Appliance::i_convertDiskAttachmentValues: hdc.system=%d, hdc.fPrimary=%d, ulAddressOnParent=%d\n",
2244 hdc.system,
2245 hdc.fPrimary,
2246 ulAddressOnParent));
2247
2248 switch (hdc.system)
2249 {
2250 case ovf::HardDiskController::IDE:
2251 // For the IDE bus, the port parameter can be either 0 or 1, to specify the primary
2252 // or secondary IDE controller, respectively. For the primary controller of the IDE bus,
2253 // the device number can be either 0 or 1, to specify the master or the slave device,
2254 // respectively. For the secondary IDE controller, the device number is always 1 because
2255 // the master device is reserved for the CD-ROM drive.
2256 controllerType = Bstr("IDE Controller");
2257 switch (ulAddressOnParent)
2258 {
2259 case 0: // master
2260 if (!hdc.fPrimary)
2261 {
2262 // secondary master
2263 lControllerPort = (long)1;
2264 lDevice = (long)0;
2265 }
2266 else // primary master
2267 {
2268 lControllerPort = (long)0;
2269 lDevice = (long)0;
2270 }
2271 break;
2272
2273 case 1: // slave
2274 if (!hdc.fPrimary)
2275 {
2276 // secondary slave
2277 lControllerPort = (long)1;
2278 lDevice = (long)1;
2279 }
2280 else // primary slave
2281 {
2282 lControllerPort = (long)0;
2283 lDevice = (long)1;
2284 }
2285 break;
2286
2287 // used by older VBox exports
2288 case 2: // interpret this as secondary master
2289 lControllerPort = (long)1;
2290 lDevice = (long)0;
2291 break;
2292
2293 // used by older VBox exports
2294 case 3: // interpret this as secondary slave
2295 lControllerPort = (long)1;
2296 lDevice = (long)1;
2297 break;
2298
2299 default:
2300 throw setError(VBOX_E_NOT_SUPPORTED,
2301 tr("Invalid channel %RI16 specified; IDE controllers support only 0, 1 or 2"),
2302 ulAddressOnParent);
2303 break;
2304 }
2305 break;
2306
2307 case ovf::HardDiskController::SATA:
2308 controllerType = Bstr("SATA Controller");
2309 lControllerPort = (long)ulAddressOnParent;
2310 lDevice = (long)0;
2311 break;
2312
2313 case ovf::HardDiskController::SCSI:
2314 {
2315 if(hdc.strControllerType.compare("lsilogicsas")==0)
2316 controllerType = Bstr("SAS Controller");
2317 else
2318 controllerType = Bstr("SCSI Controller");
2319 lControllerPort = (long)ulAddressOnParent;
2320 lDevice = (long)0;
2321 }
2322 break;
2323
2324 default: break;
2325 }
2326
2327 Log(("=> lControllerPort=%d, lDevice=%d\n", lControllerPort, lDevice));
2328}
2329
2330/**
2331 * Imports one disk image.
2332 *
2333 * This is common code shared between
2334 * -- i_importMachineGeneric() for the OVF case; in that case the information comes from
2335 * the OVF virtual systems;
2336 * -- i_importVBoxMachine(); in that case, the information comes from the <vbox:Machine>
2337 * tag.
2338 *
2339 * Both ways of describing machines use the OVF disk references section, so in both cases
2340 * the caller needs to pass in the ovf::DiskImage structure from ovfreader.cpp.
2341 *
2342 * As a result, in both cases, if di.strHref is empty, we create a new disk as per the OVF
2343 * spec, even though this cannot really happen in the vbox:Machine case since such data
2344 * would never have been exported.
2345 *
2346 * This advances stack.pProgress by one operation with the disk's weight.
2347 *
2348 * @param di ovfreader.cpp structure describing the disk image from the OVF that is to be imported
2349 * @param strTargetPath Where to create the target image.
2350 * @param pTargetHD out: The newly created target disk. This also gets pushed on stack.llHardDisksCreated for cleanup.
2351 * @param stack
2352 */
2353void Appliance::i_importOneDiskImage(const ovf::DiskImage &di,
2354 Utf8Str *pStrDstPath,
2355 ComObjPtr<Medium> &pTargetHD,
2356 ImportStack &stack)
2357{
2358 ComObjPtr<Progress> pProgress;
2359 pProgress.createObject();
2360 HRESULT rc = pProgress->init(mVirtualBox,
2361 static_cast<IAppliance*>(this),
2362 BstrFmt(tr("Creating medium '%s'"),
2363 pStrDstPath->c_str()).raw(),
2364 TRUE);
2365 if (FAILED(rc)) throw rc;
2366
2367 /* Get the system properties. */
2368 SystemProperties *pSysProps = mVirtualBox->i_getSystemProperties();
2369
2370 /* Keep the source file ref handy for later. */
2371 const Utf8Str &strSourceOVF = di.strHref;
2372
2373 /* Construct source file path */
2374 Utf8Str strSrcFilePath;
2375 if (stack.hVfsFssOva != NIL_RTVFSFSSTREAM)
2376 strSrcFilePath = strSourceOVF;
2377 else
2378 {
2379 strSrcFilePath = stack.strSourceDir;
2380 strSrcFilePath.append(RTPATH_SLASH_STR);
2381 strSrcFilePath.append(strSourceOVF);
2382 }
2383
2384 /* First of all check if the path is an UUID. If so, the user like to
2385 * import the disk into an existing path. This is useful for iSCSI for
2386 * example. */
2387 RTUUID uuid;
2388 int vrc = RTUuidFromStr(&uuid, pStrDstPath->c_str());
2389 if (vrc == VINF_SUCCESS)
2390 {
2391 rc = mVirtualBox->i_findHardDiskById(Guid(uuid), true, &pTargetHD);
2392 if (FAILED(rc)) throw rc;
2393 }
2394 else
2395 {
2396 RTVFSIOSTREAM hVfsIosSrc = NIL_RTVFSIOSTREAM;
2397
2398 /* check read file to GZIP compression */
2399 bool const fGzipped = di.strCompression.compare("gzip",Utf8Str::CaseInsensitive) == 0;
2400 Utf8Str strDeleteTemp;
2401 try
2402 {
2403 Utf8Str strTrgFormat = "VMDK";
2404 ComObjPtr<MediumFormat> trgFormat;
2405 Bstr bstrFormatName;
2406 ULONG lCabs = 0;
2407
2408 char *pszSuff = RTPathSuffix(pStrDstPath->c_str());
2409 if (pszSuff != NULL)
2410 {
2411 /*
2412 * Figure out which format the user like to have. Default is VMDK
2413 * or it can be VDI if according command-line option is set
2414 */
2415
2416 /*
2417 * We need a proper target format
2418 * if target format has been changed by user via GUI import wizard
2419 * or via VBoxManage import command (option --importtovdi)
2420 * then we need properly process such format like ISO
2421 * Because there is no conversion ISO to VDI
2422 */
2423 trgFormat = pSysProps->i_mediumFormatFromExtension(++pszSuff);
2424 if (trgFormat.isNull())
2425 throw setError(E_FAIL, tr("Unsupported medium format for disk image '%s'"), di.strHref.c_str());
2426
2427 rc = trgFormat->COMGETTER(Name)(bstrFormatName.asOutParam());
2428 if (FAILED(rc)) throw rc;
2429
2430 strTrgFormat = Utf8Str(bstrFormatName);
2431
2432 if ( m->optListImport.contains(ImportOptions_ImportToVDI)
2433 && strTrgFormat.compare("RAW", Utf8Str::CaseInsensitive) != 0)
2434 {
2435 /* change the target extension */
2436 strTrgFormat = "vdi";
2437 trgFormat = pSysProps->i_mediumFormatFromExtension(strTrgFormat);
2438 *pStrDstPath = pStrDstPath->stripSuffix();
2439 *pStrDstPath = pStrDstPath->append(".");
2440 *pStrDstPath = pStrDstPath->append(strTrgFormat.c_str());
2441 }
2442
2443 /* Check the capabilities. We need create capabilities. */
2444 lCabs = 0;
2445 com::SafeArray <MediumFormatCapabilities_T> mediumFormatCap;
2446 rc = trgFormat->COMGETTER(Capabilities)(ComSafeArrayAsOutParam(mediumFormatCap));
2447
2448 if (FAILED(rc))
2449 throw rc;
2450
2451 for (ULONG j = 0; j < mediumFormatCap.size(); j++)
2452 lCabs |= mediumFormatCap[j];
2453
2454 if ( !(lCabs & MediumFormatCapabilities_CreateFixed)
2455 && !(lCabs & MediumFormatCapabilities_CreateDynamic) )
2456 throw setError(VBOX_E_NOT_SUPPORTED,
2457 tr("Could not find a valid medium format for the target disk '%s'"),
2458 pStrDstPath->c_str());
2459 }
2460 else
2461 {
2462 throw setError(VBOX_E_FILE_ERROR,
2463 tr("The target disk '%s' has no extension "),
2464 pStrDstPath->c_str(), VERR_INVALID_NAME);
2465 }
2466
2467 /* Create an IMedium object. */
2468 pTargetHD.createObject();
2469
2470 /*CD/DVD case*/
2471 if (strTrgFormat.compare("RAW", Utf8Str::CaseInsensitive) == 0)
2472 {
2473 try
2474 {
2475 if (fGzipped)
2476 i_importDecompressFile(stack, strSrcFilePath, *pStrDstPath, strSourceOVF.c_str());
2477 else
2478 i_importCopyFile(stack, strSrcFilePath, *pStrDstPath, strSourceOVF.c_str());
2479 }
2480 catch (HRESULT /*arc*/)
2481 {
2482 throw;
2483 }
2484
2485 /* Advance to the next operation. */
2486 /* operation's weight, as set up with the IProgress originally */
2487 stack.pProgress->SetNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"),
2488 RTPathFilename(strSourceOVF.c_str())).raw(),
2489 di.ulSuggestedSizeMB);
2490 }
2491 else/* HDD case*/
2492 {
2493 rc = pTargetHD->init(mVirtualBox,
2494 strTrgFormat,
2495 *pStrDstPath,
2496 Guid::Empty /* media registry: none yet */,
2497 DeviceType_HardDisk);
2498 if (FAILED(rc)) throw rc;
2499
2500 /* Now create an empty hard disk. */
2501 rc = mVirtualBox->CreateMedium(Bstr(strTrgFormat).raw(),
2502 Bstr(*pStrDstPath).raw(),
2503 AccessMode_ReadWrite, DeviceType_HardDisk,
2504 ComPtr<IMedium>(pTargetHD).asOutParam());
2505 if (FAILED(rc)) throw rc;
2506
2507 /* If strHref is empty we have to create a new file. */
2508 if (strSourceOVF.isEmpty())
2509 {
2510 com::SafeArray<MediumVariant_T> mediumVariant;
2511 mediumVariant.push_back(MediumVariant_Standard);
2512
2513 /* Kick of the creation of a dynamic growing disk image with the given capacity. */
2514 rc = pTargetHD->CreateBaseStorage(di.iCapacity / _1M,
2515 ComSafeArrayAsInParam(mediumVariant),
2516 ComPtr<IProgress>(pProgress).asOutParam());
2517 if (FAILED(rc)) throw rc;
2518
2519 /* Advance to the next operation. */
2520 /* operation's weight, as set up with the IProgress originally */
2521 stack.pProgress->SetNextOperation(BstrFmt(tr("Creating disk image '%s'"),
2522 pStrDstPath->c_str()).raw(),
2523 di.ulSuggestedSizeMB);
2524 }
2525 else
2526 {
2527 /* We need a proper source format description */
2528 /* Which format to use? */
2529 ComObjPtr<MediumFormat> srcFormat;
2530 rc = i_findMediumFormatFromDiskImage(di, srcFormat);
2531 if (FAILED(rc))
2532 throw setError(VBOX_E_NOT_SUPPORTED,
2533 tr("Could not find a valid medium format for the source disk '%s' "
2534 "Check correctness of the image format URL in the OVF description file "
2535 "or extension of the image"),
2536 RTPathFilename(strSourceOVF.c_str()));
2537
2538 /* If gzipped, decompress the GZIP file and save a new file in the target path */
2539 if (fGzipped)
2540 {
2541 Utf8Str strTargetFilePath(*pStrDstPath);
2542 strTargetFilePath.stripFilename();
2543 strTargetFilePath.append(RTPATH_SLASH_STR);
2544 strTargetFilePath.append("temp_");
2545 strTargetFilePath.append(RTPathFilename(strSrcFilePath.c_str()));
2546 strDeleteTemp = strTargetFilePath;
2547
2548 i_importDecompressFile(stack, strSrcFilePath, strTargetFilePath, strSourceOVF.c_str());
2549
2550 /* Correct the source and the target with the actual values */
2551 strSrcFilePath = strTargetFilePath;
2552
2553 /* Open the new source file. */
2554 vrc = RTVfsIoStrmOpenNormal(strSrcFilePath.c_str(), RTFILE_O_READ | RTFILE_O_DENY_NONE | RTFILE_O_OPEN,
2555 &hVfsIosSrc);
2556 if (RT_FAILURE(vrc))
2557 throw setErrorVrc(vrc, tr("Error opening decompressed image file '%s' (%Rrc)"),
2558 strSrcFilePath.c_str(), vrc);
2559 }
2560 else
2561 hVfsIosSrc = i_importOpenSourceFile(stack, strSrcFilePath, strSourceOVF.c_str());
2562
2563 /* Start the source image cloning operation. */
2564 ComObjPtr<Medium> nullParent;
2565 rc = pTargetHD->i_importFile(strSrcFilePath.c_str(),
2566 srcFormat,
2567 MediumVariant_Standard,
2568 hVfsIosSrc,
2569 nullParent,
2570 pProgress);
2571 RTVfsIoStrmRelease(hVfsIosSrc);
2572 hVfsIosSrc = NIL_RTVFSIOSTREAM;
2573 if (FAILED(rc))
2574 throw rc;
2575
2576 /* Advance to the next operation. */
2577 /* operation's weight, as set up with the IProgress originally */
2578 stack.pProgress->SetNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"),
2579 RTPathFilename(strSourceOVF.c_str())).raw(),
2580 di.ulSuggestedSizeMB);
2581 }
2582
2583 /* Now wait for the background disk operation to complete; this throws
2584 * HRESULTs on error. */
2585 ComPtr<IProgress> pp(pProgress);
2586 i_waitForAsyncProgress(stack.pProgress, pp);
2587 }
2588 }
2589 catch (...)
2590 {
2591 if (strDeleteTemp.isNotEmpty())
2592 RTFileDelete(strDeleteTemp.c_str());
2593 throw;
2594 }
2595
2596 /* Make sure the source file is closed. */
2597 if (hVfsIosSrc != NIL_RTVFSIOSTREAM)
2598 RTVfsIoStrmRelease(hVfsIosSrc);
2599
2600 /*
2601 * Delete the temp gunzip result, if any.
2602 */
2603 if (strDeleteTemp.isNotEmpty())
2604 {
2605 vrc = RTFileDelete(strSrcFilePath.c_str());
2606 if (RT_FAILURE(vrc))
2607 setWarning(VBOX_E_FILE_ERROR,
2608 tr("Failed to delete the temporary file '%s' (%Rrc)"), strSrcFilePath.c_str(), vrc);
2609 }
2610 }
2611}
2612
2613/**
2614 * Imports one OVF virtual system (described by the given ovf::VirtualSystem and VirtualSystemDescription)
2615 * into VirtualBox by creating an IMachine instance, which is returned.
2616 *
2617 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
2618 * up any leftovers from this function. For this, the given ImportStack instance has received information
2619 * about what needs cleaning up (to support rollback).
2620 *
2621 * @param vsysThis OVF virtual system (machine) to import.
2622 * @param vsdescThis Matching virtual system description (machine) to import.
2623 * @param pNewMachine out: Newly created machine.
2624 * @param stack Cleanup stack for when this throws.
2625 */
2626void Appliance::i_importMachineGeneric(const ovf::VirtualSystem &vsysThis,
2627 ComObjPtr<VirtualSystemDescription> &vsdescThis,
2628 ComPtr<IMachine> &pNewMachine,
2629 ImportStack &stack)
2630{
2631 LogFlowFuncEnter();
2632 HRESULT rc;
2633
2634 // Get the instance of IGuestOSType which matches our string guest OS type so we
2635 // can use recommended defaults for the new machine where OVF doesn't provide any
2636 ComPtr<IGuestOSType> osType;
2637 rc = mVirtualBox->GetGuestOSType(Bstr(stack.strOsTypeVBox).raw(), osType.asOutParam());
2638 if (FAILED(rc)) throw rc;
2639
2640 /* Create the machine */
2641 SafeArray<BSTR> groups; /* no groups */
2642 rc = mVirtualBox->CreateMachine(NULL, /* machine name: use default */
2643 Bstr(stack.strNameVBox).raw(),
2644 ComSafeArrayAsInParam(groups),
2645 Bstr(stack.strOsTypeVBox).raw(),
2646 NULL, /* aCreateFlags */
2647 pNewMachine.asOutParam());
2648 if (FAILED(rc)) throw rc;
2649
2650 // set the description
2651 if (!stack.strDescription.isEmpty())
2652 {
2653 rc = pNewMachine->COMSETTER(Description)(Bstr(stack.strDescription).raw());
2654 if (FAILED(rc)) throw rc;
2655 }
2656
2657 // CPU count
2658 rc = pNewMachine->COMSETTER(CPUCount)(stack.cCPUs);
2659 if (FAILED(rc)) throw rc;
2660
2661 if (stack.fForceHWVirt)
2662 {
2663 rc = pNewMachine->SetHWVirtExProperty(HWVirtExPropertyType_Enabled, TRUE);
2664 if (FAILED(rc)) throw rc;
2665 }
2666
2667 // RAM
2668 rc = pNewMachine->COMSETTER(MemorySize)(stack.ulMemorySizeMB);
2669 if (FAILED(rc)) throw rc;
2670
2671 /* VRAM */
2672 /* Get the recommended VRAM for this guest OS type */
2673 ULONG vramVBox;
2674 rc = osType->COMGETTER(RecommendedVRAM)(&vramVBox);
2675 if (FAILED(rc)) throw rc;
2676
2677 /* Set the VRAM */
2678 rc = pNewMachine->COMSETTER(VRAMSize)(vramVBox);
2679 if (FAILED(rc)) throw rc;
2680
2681 // I/O APIC: Generic OVF has no setting for this. Enable it if we
2682 // import a Windows VM because if if Windows was installed without IOAPIC,
2683 // it will not mind finding an one later on, but if Windows was installed
2684 // _with_ an IOAPIC, it will bluescreen if it's not found
2685 if (!stack.fForceIOAPIC)
2686 {
2687 Bstr bstrFamilyId;
2688 rc = osType->COMGETTER(FamilyId)(bstrFamilyId.asOutParam());
2689 if (FAILED(rc)) throw rc;
2690 if (bstrFamilyId == "Windows")
2691 stack.fForceIOAPIC = true;
2692 }
2693
2694 if (stack.fForceIOAPIC)
2695 {
2696 ComPtr<IBIOSSettings> pBIOSSettings;
2697 rc = pNewMachine->COMGETTER(BIOSSettings)(pBIOSSettings.asOutParam());
2698 if (FAILED(rc)) throw rc;
2699
2700 rc = pBIOSSettings->COMSETTER(IOAPICEnabled)(TRUE);
2701 if (FAILED(rc)) throw rc;
2702 }
2703
2704 if (!stack.strAudioAdapter.isEmpty())
2705 if (stack.strAudioAdapter.compare("null", Utf8Str::CaseInsensitive) != 0)
2706 {
2707 uint32_t audio = RTStrToUInt32(stack.strAudioAdapter.c_str()); // should be 0 for AC97
2708 ComPtr<IAudioAdapter> audioAdapter;
2709 rc = pNewMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam());
2710 if (FAILED(rc)) throw rc;
2711 rc = audioAdapter->COMSETTER(Enabled)(true);
2712 if (FAILED(rc)) throw rc;
2713 rc = audioAdapter->COMSETTER(AudioController)(static_cast<AudioControllerType_T>(audio));
2714 if (FAILED(rc)) throw rc;
2715 }
2716
2717#ifdef VBOX_WITH_USB
2718 /* USB Controller */
2719 if (stack.fUSBEnabled)
2720 {
2721 ComPtr<IUSBController> usbController;
2722 rc = pNewMachine->AddUSBController(Bstr("OHCI").raw(), USBControllerType_OHCI, usbController.asOutParam());
2723 if (FAILED(rc)) throw rc;
2724 }
2725#endif /* VBOX_WITH_USB */
2726
2727 /* Change the network adapters */
2728 uint32_t maxNetworkAdapters = Global::getMaxNetworkAdapters(ChipsetType_PIIX3);
2729
2730 std::list<VirtualSystemDescriptionEntry*> vsdeNW = vsdescThis->i_findByType(VirtualSystemDescriptionType_NetworkAdapter);
2731 if (vsdeNW.empty())
2732 {
2733 /* No network adapters, so we have to disable our default one */
2734 ComPtr<INetworkAdapter> nwVBox;
2735 rc = pNewMachine->GetNetworkAdapter(0, nwVBox.asOutParam());
2736 if (FAILED(rc)) throw rc;
2737 rc = nwVBox->COMSETTER(Enabled)(false);
2738 if (FAILED(rc)) throw rc;
2739 }
2740 else if (vsdeNW.size() > maxNetworkAdapters)
2741 throw setError(VBOX_E_FILE_ERROR,
2742 tr("Too many network adapters: OVF requests %d network adapters, "
2743 "but VirtualBox only supports %d"),
2744 vsdeNW.size(), maxNetworkAdapters);
2745 else
2746 {
2747 list<VirtualSystemDescriptionEntry*>::const_iterator nwIt;
2748 size_t a = 0;
2749 for (nwIt = vsdeNW.begin();
2750 nwIt != vsdeNW.end();
2751 ++nwIt, ++a)
2752 {
2753 const VirtualSystemDescriptionEntry* pvsys = *nwIt;
2754
2755 const Utf8Str &nwTypeVBox = pvsys->strVBoxCurrent;
2756 uint32_t tt1 = RTStrToUInt32(nwTypeVBox.c_str());
2757 ComPtr<INetworkAdapter> pNetworkAdapter;
2758 rc = pNewMachine->GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
2759 if (FAILED(rc)) throw rc;
2760 /* Enable the network card & set the adapter type */
2761 rc = pNetworkAdapter->COMSETTER(Enabled)(true);
2762 if (FAILED(rc)) throw rc;
2763 rc = pNetworkAdapter->COMSETTER(AdapterType)(static_cast<NetworkAdapterType_T>(tt1));
2764 if (FAILED(rc)) throw rc;
2765
2766 // default is NAT; change to "bridged" if extra conf says so
2767 if (pvsys->strExtraConfigCurrent.endsWith("type=Bridged", Utf8Str::CaseInsensitive))
2768 {
2769 /* Attach to the right interface */
2770 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_Bridged);
2771 if (FAILED(rc)) throw rc;
2772 ComPtr<IHost> host;
2773 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
2774 if (FAILED(rc)) throw rc;
2775 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
2776 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
2777 if (FAILED(rc)) throw rc;
2778 // We search for the first host network interface which
2779 // is usable for bridged networking
2780 for (size_t j = 0;
2781 j < nwInterfaces.size();
2782 ++j)
2783 {
2784 HostNetworkInterfaceType_T itype;
2785 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
2786 if (FAILED(rc)) throw rc;
2787 if (itype == HostNetworkInterfaceType_Bridged)
2788 {
2789 Bstr name;
2790 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
2791 if (FAILED(rc)) throw rc;
2792 /* Set the interface name to attach to */
2793 rc = pNetworkAdapter->COMSETTER(BridgedInterface)(name.raw());
2794 if (FAILED(rc)) throw rc;
2795 break;
2796 }
2797 }
2798 }
2799 /* Next test for host only interfaces */
2800 else if (pvsys->strExtraConfigCurrent.endsWith("type=HostOnly", Utf8Str::CaseInsensitive))
2801 {
2802 /* Attach to the right interface */
2803 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_HostOnly);
2804 if (FAILED(rc)) throw rc;
2805 ComPtr<IHost> host;
2806 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
2807 if (FAILED(rc)) throw rc;
2808 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
2809 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
2810 if (FAILED(rc)) throw rc;
2811 // We search for the first host network interface which
2812 // is usable for host only networking
2813 for (size_t j = 0;
2814 j < nwInterfaces.size();
2815 ++j)
2816 {
2817 HostNetworkInterfaceType_T itype;
2818 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
2819 if (FAILED(rc)) throw rc;
2820 if (itype == HostNetworkInterfaceType_HostOnly)
2821 {
2822 Bstr name;
2823 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
2824 if (FAILED(rc)) throw rc;
2825 /* Set the interface name to attach to */
2826 rc = pNetworkAdapter->COMSETTER(HostOnlyInterface)(name.raw());
2827 if (FAILED(rc)) throw rc;
2828 break;
2829 }
2830 }
2831 }
2832 /* Next test for internal interfaces */
2833 else if (pvsys->strExtraConfigCurrent.endsWith("type=Internal", Utf8Str::CaseInsensitive))
2834 {
2835 /* Attach to the right interface */
2836 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_Internal);
2837 if (FAILED(rc)) throw rc;
2838 }
2839 /* Next test for Generic interfaces */
2840 else if (pvsys->strExtraConfigCurrent.endsWith("type=Generic", Utf8Str::CaseInsensitive))
2841 {
2842 /* Attach to the right interface */
2843 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_Generic);
2844 if (FAILED(rc)) throw rc;
2845 }
2846
2847 /* Next test for NAT network interfaces */
2848 else if (pvsys->strExtraConfigCurrent.endsWith("type=NATNetwork", Utf8Str::CaseInsensitive))
2849 {
2850 /* Attach to the right interface */
2851 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_NATNetwork);
2852 if (FAILED(rc)) throw rc;
2853 com::SafeIfaceArray<INATNetwork> nwNATNetworks;
2854 rc = mVirtualBox->COMGETTER(NATNetworks)(ComSafeArrayAsOutParam(nwNATNetworks));
2855 if (FAILED(rc)) throw rc;
2856 // Pick the first NAT network (if there is any)
2857 if (nwNATNetworks.size())
2858 {
2859 Bstr name;
2860 rc = nwNATNetworks[0]->COMGETTER(NetworkName)(name.asOutParam());
2861 if (FAILED(rc)) throw rc;
2862 /* Set the NAT network name to attach to */
2863 rc = pNetworkAdapter->COMSETTER(NATNetwork)(name.raw());
2864 if (FAILED(rc)) throw rc;
2865 break;
2866 }
2867 }
2868 }
2869 }
2870
2871 // IDE Hard disk controller
2872 std::list<VirtualSystemDescriptionEntry*> vsdeHDCIDE =
2873 vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskControllerIDE);
2874 /*
2875 * In OVF (at least VMware's version of it), an IDE controller has two ports,
2876 * so VirtualBox's single IDE controller with two channels and two ports each counts as
2877 * two OVF IDE controllers -- so we accept one or two such IDE controllers
2878 */
2879 size_t cIDEControllers = vsdeHDCIDE.size();
2880 if (cIDEControllers > 2)
2881 throw setError(VBOX_E_FILE_ERROR,
2882 tr("Too many IDE controllers in OVF; import facility only supports two"));
2883 if (!vsdeHDCIDE.empty())
2884 {
2885 // one or two IDE controllers present in OVF: add one VirtualBox controller
2886 ComPtr<IStorageController> pController;
2887 rc = pNewMachine->AddStorageController(Bstr("IDE Controller").raw(), StorageBus_IDE, pController.asOutParam());
2888 if (FAILED(rc)) throw rc;
2889
2890 const char *pcszIDEType = vsdeHDCIDE.front()->strVBoxCurrent.c_str();
2891 if (!strcmp(pcszIDEType, "PIIX3"))
2892 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX3);
2893 else if (!strcmp(pcszIDEType, "PIIX4"))
2894 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX4);
2895 else if (!strcmp(pcszIDEType, "ICH6"))
2896 rc = pController->COMSETTER(ControllerType)(StorageControllerType_ICH6);
2897 else
2898 throw setError(VBOX_E_FILE_ERROR,
2899 tr("Invalid IDE controller type \"%s\""),
2900 pcszIDEType);
2901 if (FAILED(rc)) throw rc;
2902 }
2903
2904 /* Hard disk controller SATA */
2905 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSATA =
2906 vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskControllerSATA);
2907 if (vsdeHDCSATA.size() > 1)
2908 throw setError(VBOX_E_FILE_ERROR,
2909 tr("Too many SATA controllers in OVF; import facility only supports one"));
2910 if (!vsdeHDCSATA.empty())
2911 {
2912 ComPtr<IStorageController> pController;
2913 const Utf8Str &hdcVBox = vsdeHDCSATA.front()->strVBoxCurrent;
2914 if (hdcVBox == "AHCI")
2915 {
2916 rc = pNewMachine->AddStorageController(Bstr("SATA Controller").raw(),
2917 StorageBus_SATA,
2918 pController.asOutParam());
2919 if (FAILED(rc)) throw rc;
2920 }
2921 else
2922 throw setError(VBOX_E_FILE_ERROR,
2923 tr("Invalid SATA controller type \"%s\""),
2924 hdcVBox.c_str());
2925 }
2926
2927 /* Hard disk controller SCSI */
2928 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSCSI =
2929 vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskControllerSCSI);
2930 if (vsdeHDCSCSI.size() > 1)
2931 throw setError(VBOX_E_FILE_ERROR,
2932 tr("Too many SCSI controllers in OVF; import facility only supports one"));
2933 if (!vsdeHDCSCSI.empty())
2934 {
2935 ComPtr<IStorageController> pController;
2936 Bstr bstrName(L"SCSI Controller");
2937 StorageBus_T busType = StorageBus_SCSI;
2938 StorageControllerType_T controllerType;
2939 const Utf8Str &hdcVBox = vsdeHDCSCSI.front()->strVBoxCurrent;
2940 if (hdcVBox == "LsiLogic")
2941 controllerType = StorageControllerType_LsiLogic;
2942 else if (hdcVBox == "LsiLogicSas")
2943 {
2944 // OVF treats LsiLogicSas as a SCSI controller but VBox considers it a class of its own
2945 bstrName = L"SAS Controller";
2946 busType = StorageBus_SAS;
2947 controllerType = StorageControllerType_LsiLogicSas;
2948 }
2949 else if (hdcVBox == "BusLogic")
2950 controllerType = StorageControllerType_BusLogic;
2951 else
2952 throw setError(VBOX_E_FILE_ERROR,
2953 tr("Invalid SCSI controller type \"%s\""),
2954 hdcVBox.c_str());
2955
2956 rc = pNewMachine->AddStorageController(bstrName.raw(), busType, pController.asOutParam());
2957 if (FAILED(rc)) throw rc;
2958 rc = pController->COMSETTER(ControllerType)(controllerType);
2959 if (FAILED(rc)) throw rc;
2960 }
2961
2962 /* Hard disk controller SAS */
2963 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSAS =
2964 vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskControllerSAS);
2965 if (vsdeHDCSAS.size() > 1)
2966 throw setError(VBOX_E_FILE_ERROR,
2967 tr("Too many SAS controllers in OVF; import facility only supports one"));
2968 if (!vsdeHDCSAS.empty())
2969 {
2970 ComPtr<IStorageController> pController;
2971 rc = pNewMachine->AddStorageController(Bstr(L"SAS Controller").raw(),
2972 StorageBus_SAS,
2973 pController.asOutParam());
2974 if (FAILED(rc)) throw rc;
2975 rc = pController->COMSETTER(ControllerType)(StorageControllerType_LsiLogicSas);
2976 if (FAILED(rc)) throw rc;
2977 }
2978
2979 /* Now its time to register the machine before we add any hard disks */
2980 rc = mVirtualBox->RegisterMachine(pNewMachine);
2981 if (FAILED(rc)) throw rc;
2982
2983 // store new machine for roll-back in case of errors
2984 Bstr bstrNewMachineId;
2985 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
2986 if (FAILED(rc)) throw rc;
2987 Guid uuidNewMachine(bstrNewMachineId);
2988 m->llGuidsMachinesCreated.push_back(uuidNewMachine);
2989
2990 // Add floppies and CD-ROMs to the appropriate controllers.
2991 std::list<VirtualSystemDescriptionEntry*> vsdeFloppy = vsdescThis->i_findByType(VirtualSystemDescriptionType_Floppy);
2992 if (vsdeFloppy.size() > 1)
2993 throw setError(VBOX_E_FILE_ERROR,
2994 tr("Too many floppy controllers in OVF; import facility only supports one"));
2995 std::list<VirtualSystemDescriptionEntry*> vsdeCDROM = vsdescThis->i_findByType(VirtualSystemDescriptionType_CDROM);
2996 if ( !vsdeFloppy.empty()
2997 || !vsdeCDROM.empty()
2998 )
2999 {
3000 // If there's an error here we need to close the session, so
3001 // we need another try/catch block.
3002
3003 try
3004 {
3005 // to attach things we need to open a session for the new machine
3006 rc = pNewMachine->LockMachine(stack.pSession, LockType_Write);
3007 if (FAILED(rc)) throw rc;
3008 stack.fSessionOpen = true;
3009
3010 ComPtr<IMachine> sMachine;
3011 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
3012 if (FAILED(rc)) throw rc;
3013
3014 // floppy first
3015 if (vsdeFloppy.size() == 1)
3016 {
3017 ComPtr<IStorageController> pController;
3018 rc = sMachine->AddStorageController(Bstr("Floppy Controller").raw(),
3019 StorageBus_Floppy,
3020 pController.asOutParam());
3021 if (FAILED(rc)) throw rc;
3022
3023 Bstr bstrName;
3024 rc = pController->COMGETTER(Name)(bstrName.asOutParam());
3025 if (FAILED(rc)) throw rc;
3026
3027 // this is for rollback later
3028 MyHardDiskAttachment mhda;
3029 mhda.pMachine = pNewMachine;
3030 mhda.controllerType = bstrName;
3031 mhda.lControllerPort = 0;
3032 mhda.lDevice = 0;
3033
3034 Log(("Attaching floppy\n"));
3035
3036 rc = sMachine->AttachDevice(mhda.controllerType.raw(),
3037 mhda.lControllerPort,
3038 mhda.lDevice,
3039 DeviceType_Floppy,
3040 NULL);
3041 if (FAILED(rc)) throw rc;
3042
3043 stack.llHardDiskAttachments.push_back(mhda);
3044 }
3045
3046 rc = sMachine->SaveSettings();
3047 if (FAILED(rc)) throw rc;
3048
3049 // only now that we're done with all disks, close the session
3050 rc = stack.pSession->UnlockMachine();
3051 if (FAILED(rc)) throw rc;
3052 stack.fSessionOpen = false;
3053 }
3054 catch(HRESULT aRC)
3055 {
3056 com::ErrorInfo info;
3057
3058 if (stack.fSessionOpen)
3059 stack.pSession->UnlockMachine();
3060
3061 if (info.isFullAvailable())
3062 throw setError(aRC, Utf8Str(info.getText()).c_str());
3063 else
3064 throw setError(aRC, "Unknown error during OVF import");
3065 }
3066 }
3067
3068 // create the hard disks & connect them to the appropriate controllers
3069 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskImage);
3070 if (!avsdeHDs.empty())
3071 {
3072 // If there's an error here we need to close the session, so
3073 // we need another try/catch block.
3074 try
3075 {
3076#ifdef LOG_ENABLED
3077 if (LogIsEnabled())
3078 {
3079 size_t i = 0;
3080 for (list<VirtualSystemDescriptionEntry*>::const_iterator itHD = avsdeHDs.begin();
3081 itHD != avsdeHDs.end(); ++itHD, i++)
3082 Log(("avsdeHDs[%zu]: strRef=%s strOvf=%s\n", i, (*itHD)->strRef.c_str(), (*itHD)->strOvf.c_str()));
3083 i = 0;
3084 for (ovf::DiskImagesMap::const_iterator itDisk = stack.mapDisks.begin(); itDisk != stack.mapDisks.end(); ++itDisk)
3085 Log(("mapDisks[%zu]: strDiskId=%s strHref=%s\n",
3086 i, itDisk->second.strDiskId.c_str(), itDisk->second.strHref.c_str()));
3087
3088 }
3089#endif
3090
3091 // to attach things we need to open a session for the new machine
3092 rc = pNewMachine->LockMachine(stack.pSession, LockType_Write);
3093 if (FAILED(rc)) throw rc;
3094 stack.fSessionOpen = true;
3095
3096 /* get VM name from virtual system description. Only one record is possible (size of list is equal 1). */
3097 std::list<VirtualSystemDescriptionEntry*> vmName = vsdescThis->i_findByType(VirtualSystemDescriptionType_Name);
3098 std::list<VirtualSystemDescriptionEntry*>::iterator vmNameIt = vmName.begin();
3099 VirtualSystemDescriptionEntry* vmNameEntry = *vmNameIt;
3100
3101
3102 ovf::DiskImagesMap::const_iterator oit = stack.mapDisks.begin();
3103 std::set<RTCString> disksResolvedNames;
3104
3105 uint32_t cImportedDisks = 0;
3106
3107 while (oit != stack.mapDisks.end() && cImportedDisks != avsdeHDs.size())
3108 {
3109/** @todo r=bird: Most of the code here is duplicated in the other machine
3110 * import method, factor out. */
3111 ovf::DiskImage diCurrent = oit->second;
3112
3113 Log(("diCurrent.strDiskId=%s diCurrent.strHref=%s\n", diCurrent.strDiskId.c_str(), diCurrent.strHref.c_str()));
3114 /* Iterate over all given disk images of the virtual system
3115 * disks description. We need to find the target disk path,
3116 * which could be changed by the user. */
3117 VirtualSystemDescriptionEntry *vsdeTargetHD = NULL;
3118 for (list<VirtualSystemDescriptionEntry*>::const_iterator itHD = avsdeHDs.begin();
3119 itHD != avsdeHDs.end();
3120 ++itHD)
3121 {
3122 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
3123 if (vsdeHD->strRef == diCurrent.strDiskId)
3124 {
3125 vsdeTargetHD = vsdeHD;
3126 break;
3127 }
3128 }
3129 if (!vsdeTargetHD)
3130 {
3131 /* possible case if a disk image belongs to other virtual system (OVF package with multiple VMs inside) */
3132 Log1Warning(("OVA/OVF import: Disk image %s was missed during import of VM %s\n",
3133 oit->first.c_str(), vmNameEntry->strOvf.c_str()));
3134 NOREF(vmNameEntry);
3135 ++oit;
3136 continue;
3137 }
3138
3139 //diCurrent.strDiskId contains the disk identifier (e.g. "vmdisk1"), which should exist
3140 //in the virtual system's disks map under that ID and also in the global images map
3141 ovf::VirtualDisksMap::const_iterator itVDisk = vsysThis.mapVirtualDisks.find(diCurrent.strDiskId);
3142 if (itVDisk == vsysThis.mapVirtualDisks.end())
3143 throw setError(E_FAIL,
3144 tr("Internal inconsistency looking up disk image '%s'"),
3145 diCurrent.strHref.c_str());
3146
3147 /*
3148 * preliminary check availability of the image
3149 * This step is useful if image is placed in the OVA (TAR) package
3150 */
3151 if (stack.hVfsFssOva != NIL_RTVFSFSSTREAM)
3152 {
3153 /* It means that we possibly have imported the storage earlier on the previous loop steps*/
3154 std::set<RTCString>::const_iterator h = disksResolvedNames.find(diCurrent.strHref);
3155 if (h != disksResolvedNames.end())
3156 {
3157 /* Yes, disk name was found, we can skip it*/
3158 ++oit;
3159 continue;
3160 }
3161l_skipped:
3162 rc = i_preCheckImageAvailability(stack);
3163 if (SUCCEEDED(rc))
3164 {
3165 /* current opened file isn't the same as passed one */
3166 if (RTStrICmp(diCurrent.strHref.c_str(), stack.pszOvaLookAheadName) != 0)
3167 {
3168 /* availableImage contains the disk file reference (e.g. "disk1.vmdk"), which should
3169 * exist in the global images map.
3170 * And find the disk from the OVF's disk list */
3171 ovf::DiskImagesMap::const_iterator itDiskImage;
3172 for (itDiskImage = stack.mapDisks.begin();
3173 itDiskImage != stack.mapDisks.end();
3174 itDiskImage++)
3175 if (itDiskImage->second.strHref.compare(stack.pszOvaLookAheadName,
3176 Utf8Str::CaseInsensitive) == 0)
3177 break;
3178 if (itDiskImage == stack.mapDisks.end())
3179 {
3180 LogFunc(("Skipping '%s'\n", stack.pszOvaLookAheadName));
3181 RTVfsIoStrmRelease(stack.claimOvaLookAHead());
3182 goto l_skipped;
3183 }
3184
3185 /* replace with a new found disk image */
3186 diCurrent = *(&itDiskImage->second);
3187
3188 /*
3189 * Again iterate over all given disk images of the virtual system
3190 * disks description using the found disk image
3191 */
3192 for (list<VirtualSystemDescriptionEntry*>::const_iterator itHD = avsdeHDs.begin();
3193 itHD != avsdeHDs.end();
3194 ++itHD)
3195 {
3196 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
3197 if (vsdeHD->strRef == diCurrent.strDiskId)
3198 {
3199 vsdeTargetHD = vsdeHD;
3200 break;
3201 }
3202 }
3203
3204 /*
3205 * in this case it's an error because something is wrong with the OVF description file.
3206 * May be VBox imports OVA package with wrong file sequence inside the archive.
3207 */
3208 if (!vsdeTargetHD)
3209 throw setError(E_FAIL,
3210 tr("Internal inconsistency looking up disk image '%s'"),
3211 diCurrent.strHref.c_str());
3212
3213 itVDisk = vsysThis.mapVirtualDisks.find(diCurrent.strDiskId);
3214 if (itVDisk == vsysThis.mapVirtualDisks.end())
3215 throw setError(E_FAIL,
3216 tr("Internal inconsistency looking up disk image '%s'"),
3217 diCurrent.strHref.c_str());
3218 }
3219 else
3220 {
3221 ++oit;
3222 }
3223 }
3224 else
3225 {
3226 ++oit;
3227 continue;
3228 }
3229 }
3230 else
3231 {
3232 /* just continue with normal files*/
3233 ++oit;
3234 }
3235
3236 /* very important to store disk name for the next checks */
3237 disksResolvedNames.insert(diCurrent.strHref);
3238////// end of duplicated code.
3239 const ovf::VirtualDisk &ovfVdisk = itVDisk->second;
3240
3241 ComObjPtr<Medium> pTargetHD;
3242
3243 Utf8Str savedVBoxCurrent = vsdeTargetHD->strVBoxCurrent;
3244
3245 i_importOneDiskImage(diCurrent,
3246 &vsdeTargetHD->strVBoxCurrent,
3247 pTargetHD,
3248 stack);
3249
3250 // now use the new uuid to attach the disk image to our new machine
3251 ComPtr<IMachine> sMachine;
3252 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
3253 if (FAILED(rc))
3254 throw rc;
3255
3256 // find the hard disk controller to which we should attach
3257 ovf::HardDiskController hdc = (*vsysThis.mapControllers.find(ovfVdisk.idController)).second;
3258
3259 // this is for rollback later
3260 MyHardDiskAttachment mhda;
3261 mhda.pMachine = pNewMachine;
3262
3263 i_convertDiskAttachmentValues(hdc,
3264 ovfVdisk.ulAddressOnParent,
3265 mhda.controllerType, // Bstr
3266 mhda.lControllerPort,
3267 mhda.lDevice);
3268
3269 Log(("Attaching disk %s to port %d on device %d\n",
3270 vsdeTargetHD->strVBoxCurrent.c_str(), mhda.lControllerPort, mhda.lDevice));
3271
3272 ComObjPtr<MediumFormat> mediumFormat;
3273 rc = i_findMediumFormatFromDiskImage(diCurrent, mediumFormat);
3274 if (FAILED(rc))
3275 throw rc;
3276
3277 Bstr bstrFormatName;
3278 rc = mediumFormat->COMGETTER(Name)(bstrFormatName.asOutParam());
3279 if (FAILED(rc))
3280 throw rc;
3281
3282 Utf8Str vdf = Utf8Str(bstrFormatName);
3283
3284 if (vdf.compare("RAW", Utf8Str::CaseInsensitive) == 0)
3285 {
3286 ComPtr<IMedium> dvdImage(pTargetHD);
3287
3288 rc = mVirtualBox->OpenMedium(Bstr(vsdeTargetHD->strVBoxCurrent).raw(),
3289 DeviceType_DVD,
3290 AccessMode_ReadWrite,
3291 false,
3292 dvdImage.asOutParam());
3293
3294 if (FAILED(rc))
3295 throw rc;
3296
3297 rc = sMachine->AttachDevice(mhda.controllerType.raw(),// wstring name
3298 mhda.lControllerPort, // long controllerPort
3299 mhda.lDevice, // long device
3300 DeviceType_DVD, // DeviceType_T type
3301 dvdImage);
3302 if (FAILED(rc))
3303 throw rc;
3304 }
3305 else
3306 {
3307 rc = sMachine->AttachDevice(mhda.controllerType.raw(),// wstring name
3308 mhda.lControllerPort, // long controllerPort
3309 mhda.lDevice, // long device
3310 DeviceType_HardDisk, // DeviceType_T type
3311 pTargetHD);
3312
3313 if (FAILED(rc))
3314 throw rc;
3315 }
3316
3317 stack.llHardDiskAttachments.push_back(mhda);
3318
3319 rc = sMachine->SaveSettings();
3320 if (FAILED(rc))
3321 throw rc;
3322
3323 /* restore */
3324 vsdeTargetHD->strVBoxCurrent = savedVBoxCurrent;
3325
3326 ++cImportedDisks;
3327
3328 } // end while(oit != stack.mapDisks.end())
3329
3330 /*
3331 * quantity of the imported disks isn't equal to the size of the avsdeHDs list.
3332 */
3333 if(cImportedDisks < avsdeHDs.size())
3334 {
3335 Log1Warning(("Not all disk images were imported for VM %s. Check OVF description file.",
3336 vmNameEntry->strOvf.c_str()));
3337 }
3338
3339 // only now that we're done with all disks, close the session
3340 rc = stack.pSession->UnlockMachine();
3341 if (FAILED(rc))
3342 throw rc;
3343 stack.fSessionOpen = false;
3344 }
3345 catch(HRESULT aRC)
3346 {
3347 com::ErrorInfo info;
3348 if (stack.fSessionOpen)
3349 stack.pSession->UnlockMachine();
3350
3351 if (info.isFullAvailable())
3352 throw setError(aRC, Utf8Str(info.getText()).c_str());
3353 else
3354 throw setError(aRC, "Unknown error during OVF import");
3355 }
3356 }
3357 LogFlowFuncLeave();
3358}
3359
3360/**
3361 * Imports one OVF virtual system (described by a vbox:Machine tag represented by the given config
3362 * structure) into VirtualBox by creating an IMachine instance, which is returned.
3363 *
3364 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
3365 * up any leftovers from this function. For this, the given ImportStack instance has received information
3366 * about what needs cleaning up (to support rollback).
3367 *
3368 * The machine config stored in the settings::MachineConfigFile structure contains the UUIDs of
3369 * the disk attachments used by the machine when it was exported. We also add vbox:uuid attributes
3370 * to the OVF disks sections so we can look them up. While importing these UUIDs into a second host
3371 * will most probably work, reimporting them into the same host will cause conflicts, so we always
3372 * generate new ones on import. This involves the following:
3373 *
3374 * 1) Scan the machine config for disk attachments.
3375 *
3376 * 2) For each disk attachment found, look up the OVF disk image from the disk references section
3377 * and import the disk into VirtualBox, which creates a new UUID for it. In the machine config,
3378 * replace the old UUID with the new one.
3379 *
3380 * 3) Change the machine config according to the OVF virtual system descriptions, in case the
3381 * caller has modified them using setFinalValues().
3382 *
3383 * 4) Create the VirtualBox machine with the modfified machine config.
3384 *
3385 * @param config
3386 * @param pNewMachine
3387 * @param stack
3388 */
3389void Appliance::i_importVBoxMachine(ComObjPtr<VirtualSystemDescription> &vsdescThis,
3390 ComPtr<IMachine> &pReturnNewMachine,
3391 ImportStack &stack)
3392{
3393 LogFlowFuncEnter();
3394 Assert(vsdescThis->m->pConfig);
3395
3396 HRESULT rc = S_OK;
3397
3398 settings::MachineConfigFile &config = *vsdescThis->m->pConfig;
3399
3400 /*
3401 * step 1): modify machine config according to OVF config, in case the user
3402 * has modified them using setFinalValues()
3403 */
3404
3405 /* OS Type */
3406 config.machineUserData.strOsType = stack.strOsTypeVBox;
3407 /* Description */
3408 config.machineUserData.strDescription = stack.strDescription;
3409 /* CPU count & extented attributes */
3410 config.hardwareMachine.cCPUs = stack.cCPUs;
3411 if (stack.fForceIOAPIC)
3412 config.hardwareMachine.fHardwareVirt = true;
3413 if (stack.fForceIOAPIC)
3414 config.hardwareMachine.biosSettings.fIOAPICEnabled = true;
3415 /* RAM size */
3416 config.hardwareMachine.ulMemorySizeMB = stack.ulMemorySizeMB;
3417
3418/*
3419 <const name="HardDiskControllerIDE" value="14" />
3420 <const name="HardDiskControllerSATA" value="15" />
3421 <const name="HardDiskControllerSCSI" value="16" />
3422 <const name="HardDiskControllerSAS" value="17" />
3423*/
3424
3425#ifdef VBOX_WITH_USB
3426 /* USB controller */
3427 if (stack.fUSBEnabled)
3428 {
3429 /** @todo r=klaus add support for arbitrary USB controller types, this can't handle
3430 * multiple controllers due to its design anyway */
3431 /* usually the OHCI controller is enabled already, need to check */
3432 bool fOHCIEnabled = false;
3433 settings::USBControllerList &llUSBControllers = config.hardwareMachine.usbSettings.llUSBControllers;
3434 settings::USBControllerList::iterator it;
3435 for (it = llUSBControllers.begin(); it != llUSBControllers.end(); ++it)
3436 {
3437 if (it->enmType == USBControllerType_OHCI)
3438 {
3439 fOHCIEnabled = true;
3440 break;
3441 }
3442 }
3443
3444 if (!fOHCIEnabled)
3445 {
3446 settings::USBController ctrl;
3447 ctrl.strName = "OHCI";
3448 ctrl.enmType = USBControllerType_OHCI;
3449
3450 llUSBControllers.push_back(ctrl);
3451 }
3452 }
3453 else
3454 config.hardwareMachine.usbSettings.llUSBControllers.clear();
3455#endif
3456 /* Audio adapter */
3457 if (stack.strAudioAdapter.isNotEmpty())
3458 {
3459 config.hardwareMachine.audioAdapter.fEnabled = true;
3460 config.hardwareMachine.audioAdapter.controllerType = (AudioControllerType_T)stack.strAudioAdapter.toUInt32();
3461 }
3462 else
3463 config.hardwareMachine.audioAdapter.fEnabled = false;
3464 /* Network adapter */
3465 settings::NetworkAdaptersList &llNetworkAdapters = config.hardwareMachine.llNetworkAdapters;
3466 /* First disable all network cards, they will be enabled below again. */
3467 settings::NetworkAdaptersList::iterator it1;
3468 bool fKeepAllMACs = m->optListImport.contains(ImportOptions_KeepAllMACs);
3469 bool fKeepNATMACs = m->optListImport.contains(ImportOptions_KeepNATMACs);
3470 for (it1 = llNetworkAdapters.begin(); it1 != llNetworkAdapters.end(); ++it1)
3471 {
3472 it1->fEnabled = false;
3473 if (!( fKeepAllMACs
3474 || (fKeepNATMACs && it1->mode == NetworkAttachmentType_NAT)
3475 || (fKeepNATMACs && it1->mode == NetworkAttachmentType_NATNetwork)))
3476 Host::i_generateMACAddress(it1->strMACAddress);
3477 }
3478 /* Now iterate over all network entries. */
3479 std::list<VirtualSystemDescriptionEntry*> avsdeNWs = vsdescThis->i_findByType(VirtualSystemDescriptionType_NetworkAdapter);
3480 if (!avsdeNWs.empty())
3481 {
3482 /* Iterate through all network adapter entries and search for the
3483 * corresponding one in the machine config. If one is found, configure
3484 * it based on the user settings. */
3485 list<VirtualSystemDescriptionEntry*>::const_iterator itNW;
3486 for (itNW = avsdeNWs.begin();
3487 itNW != avsdeNWs.end();
3488 ++itNW)
3489 {
3490 VirtualSystemDescriptionEntry *vsdeNW = *itNW;
3491 if ( vsdeNW->strExtraConfigCurrent.startsWith("slot=", Utf8Str::CaseInsensitive)
3492 && vsdeNW->strExtraConfigCurrent.length() > 6)
3493 {
3494 uint32_t iSlot = vsdeNW->strExtraConfigCurrent.substr(5, 1).toUInt32();
3495 /* Iterate through all network adapters in the machine config. */
3496 for (it1 = llNetworkAdapters.begin();
3497 it1 != llNetworkAdapters.end();
3498 ++it1)
3499 {
3500 /* Compare the slots. */
3501 if (it1->ulSlot == iSlot)
3502 {
3503 it1->fEnabled = true;
3504 it1->type = (NetworkAdapterType_T)vsdeNW->strVBoxCurrent.toUInt32();
3505 break;
3506 }
3507 }
3508 }
3509 }
3510 }
3511
3512 /* Floppy controller */
3513 bool fFloppy = vsdescThis->i_findByType(VirtualSystemDescriptionType_Floppy).size() > 0;
3514 /* DVD controller */
3515 bool fDVD = vsdescThis->i_findByType(VirtualSystemDescriptionType_CDROM).size() > 0;
3516 /* Iterate over all storage controller check the attachments and remove
3517 * them when necessary. Also detect broken configs with more than one
3518 * attachment. Old VirtualBox versions (prior to 3.2.10) had all disk
3519 * attachments pointing to the last hard disk image, which causes import
3520 * failures. A long fixed bug, however the OVF files are long lived. */
3521 settings::StorageControllersList &llControllers = config.storageMachine.llStorageControllers;
3522 Guid hdUuid;
3523 uint32_t cDisks = 0;
3524 bool fInconsistent = false;
3525 bool fRepairDuplicate = false;
3526 settings::StorageControllersList::iterator it3;
3527 for (it3 = llControllers.begin();
3528 it3 != llControllers.end();
3529 ++it3)
3530 {
3531 settings::AttachedDevicesList &llAttachments = it3->llAttachedDevices;
3532 settings::AttachedDevicesList::iterator it4 = llAttachments.begin();
3533 while (it4 != llAttachments.end())
3534 {
3535 if ( ( !fDVD
3536 && it4->deviceType == DeviceType_DVD)
3537 ||
3538 ( !fFloppy
3539 && it4->deviceType == DeviceType_Floppy))
3540 {
3541 it4 = llAttachments.erase(it4);
3542 continue;
3543 }
3544 else if (it4->deviceType == DeviceType_HardDisk)
3545 {
3546 const Guid &thisUuid = it4->uuid;
3547 cDisks++;
3548 if (cDisks == 1)
3549 {
3550 if (hdUuid.isZero())
3551 hdUuid = thisUuid;
3552 else
3553 fInconsistent = true;
3554 }
3555 else
3556 {
3557 if (thisUuid.isZero())
3558 fInconsistent = true;
3559 else if (thisUuid == hdUuid)
3560 fRepairDuplicate = true;
3561 }
3562 }
3563 ++it4;
3564 }
3565 }
3566 /* paranoia... */
3567 if (fInconsistent || cDisks == 1)
3568 fRepairDuplicate = false;
3569
3570 /*
3571 * step 2: scan the machine config for media attachments
3572 */
3573 /* get VM name from virtual system description. Only one record is possible (size of list is equal 1). */
3574 std::list<VirtualSystemDescriptionEntry*> vmName = vsdescThis->i_findByType(VirtualSystemDescriptionType_Name);
3575 std::list<VirtualSystemDescriptionEntry*>::iterator vmNameIt = vmName.begin();
3576 VirtualSystemDescriptionEntry* vmNameEntry = *vmNameIt;
3577
3578 /* Get all hard disk descriptions. */
3579 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskImage);
3580 std::list<VirtualSystemDescriptionEntry*>::iterator avsdeHDsIt = avsdeHDs.begin();
3581 /* paranoia - if there is no 1:1 match do not try to repair. */
3582 if (cDisks != avsdeHDs.size())
3583 fRepairDuplicate = false;
3584
3585 // there must be an image in the OVF disk structs with the same UUID
3586
3587 ovf::DiskImagesMap::const_iterator oit = stack.mapDisks.begin();
3588 std::set<RTCString> disksResolvedNames;
3589
3590 uint32_t cImportedDisks = 0;
3591
3592 while (oit != stack.mapDisks.end() && cImportedDisks != avsdeHDs.size())
3593 {
3594/** @todo r=bird: Most of the code here is duplicated in the other machine
3595 * import method, factor out. */
3596 ovf::DiskImage diCurrent = oit->second;
3597
3598 Log(("diCurrent.strDiskId=%s diCurrent.strHref=%s\n", diCurrent.strDiskId.c_str(), diCurrent.strHref.c_str()));
3599
3600 /* Iterate over all given disk images of the virtual system
3601 * disks description. We need to find the target disk path,
3602 * which could be changed by the user. */
3603 VirtualSystemDescriptionEntry *vsdeTargetHD = NULL;
3604 for (list<VirtualSystemDescriptionEntry*>::const_iterator itHD = avsdeHDs.begin();
3605 itHD != avsdeHDs.end();
3606 ++itHD)
3607 {
3608 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
3609 if (vsdeHD->strRef == oit->first)
3610 {
3611 vsdeTargetHD = vsdeHD;
3612 break;
3613 }
3614 }
3615 if (!vsdeTargetHD)
3616 {
3617 /* possible case if a disk image belongs to other virtual system (OVF package with multiple VMs inside) */
3618 Log1Warning(("OVA/OVF import: Disk image %s was missed during import of VM %s\n",
3619 oit->first.c_str(), vmNameEntry->strOvf.c_str()));
3620 NOREF(vmNameEntry);
3621 ++oit;
3622 continue;
3623 }
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633 /*
3634 * preliminary check availability of the image
3635 * This step is useful if image is placed in the OVA (TAR) package
3636 */
3637 if (stack.hVfsFssOva != NIL_RTVFSFSSTREAM)
3638 {
3639 /* It means that we possibly have imported the storage earlier on a previous loop step. */
3640 std::set<RTCString>::const_iterator h = disksResolvedNames.find(diCurrent.strHref);
3641 if (h != disksResolvedNames.end())
3642 {
3643 /* Yes, disk name was found, we can skip it*/
3644 ++oit;
3645 continue;
3646 }
3647l_skipped:
3648 rc = i_preCheckImageAvailability(stack);
3649 if (SUCCEEDED(rc))
3650 {
3651 /* current opened file isn't the same as passed one */
3652 if (RTStrICmp(diCurrent.strHref.c_str(), stack.pszOvaLookAheadName) != 0)
3653 {
3654 // availableImage contains the disk identifier (e.g. "vmdisk1"), which should exist
3655 // in the virtual system's disks map under that ID and also in the global images map
3656 // and find the disk from the OVF's disk list
3657 ovf::DiskImagesMap::const_iterator itDiskImage;
3658 for (itDiskImage = stack.mapDisks.begin();
3659 itDiskImage != stack.mapDisks.end();
3660 itDiskImage++)
3661 if (itDiskImage->second.strHref.compare(stack.pszOvaLookAheadName,
3662 Utf8Str::CaseInsensitive) == 0)
3663 break;
3664 if (itDiskImage == stack.mapDisks.end())
3665 {
3666 LogFunc(("Skipping '%s'\n", stack.pszOvaLookAheadName));
3667 RTVfsIoStrmRelease(stack.claimOvaLookAHead());
3668 goto l_skipped;
3669 }
3670 //throw setError(E_FAIL,
3671 // tr("Internal inconsistency looking up disk image '%s'. "
3672 // "Check compliance OVA package structure and file names "
3673 // "references in the section <References> in the OVF file."),
3674 // stack.pszOvaLookAheadName);
3675
3676 /* replace with a new found disk image */
3677 diCurrent = *(&itDiskImage->second);
3678
3679 /*
3680 * Again iterate over all given disk images of the virtual system
3681 * disks description using the found disk image
3682 */
3683 for (list<VirtualSystemDescriptionEntry*>::const_iterator itHD = avsdeHDs.begin();
3684 itHD != avsdeHDs.end();
3685 ++itHD)
3686 {
3687 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
3688 if (vsdeHD->strRef == diCurrent.strDiskId)
3689 {
3690 vsdeTargetHD = vsdeHD;
3691 break;
3692 }
3693 }
3694
3695 /*
3696 * in this case it's an error because something is wrong with the OVF description file.
3697 * May be VBox imports OVA package with wrong file sequence inside the archive.
3698 */
3699 if (!vsdeTargetHD)
3700 throw setError(E_FAIL,
3701 tr("Internal inconsistency looking up disk image '%s'"),
3702 diCurrent.strHref.c_str());
3703
3704
3705
3706
3707
3708 }
3709 else
3710 {
3711 ++oit;
3712 }
3713 }
3714 else
3715 {
3716 ++oit;
3717 continue;
3718 }
3719 }
3720 else
3721 {
3722 /* just continue with normal files*/
3723 ++oit;
3724 }
3725
3726 /* Important! to store disk name for the next checks */
3727 disksResolvedNames.insert(diCurrent.strHref);
3728////// end of duplicated code.
3729 // there must be an image in the OVF disk structs with the same UUID
3730 bool fFound = false;
3731 Utf8Str strUuid;
3732
3733 // for each storage controller...
3734 for (settings::StorageControllersList::iterator sit = config.storageMachine.llStorageControllers.begin();
3735 sit != config.storageMachine.llStorageControllers.end();
3736 ++sit)
3737 {
3738 settings::StorageController &sc = *sit;
3739
3740 // find the OVF virtual system description entry for this storage controller
3741 switch (sc.storageBus)
3742 {
3743 case StorageBus_SATA:
3744 break;
3745 case StorageBus_SCSI:
3746 break;
3747 case StorageBus_IDE:
3748 break;
3749 case StorageBus_SAS:
3750 break;
3751 }
3752
3753 // for each medium attachment to this controller...
3754 for (settings::AttachedDevicesList::iterator dit = sc.llAttachedDevices.begin();
3755 dit != sc.llAttachedDevices.end();
3756 ++dit)
3757 {
3758 settings::AttachedDevice &d = *dit;
3759
3760 if (d.uuid.isZero())
3761 // empty DVD and floppy media
3762 continue;
3763
3764 // When repairing a broken VirtualBox xml config section (written
3765 // by VirtualBox versions earlier than 3.2.10) assume the disks
3766 // show up in the same order as in the OVF description.
3767 if (fRepairDuplicate)
3768 {
3769 VirtualSystemDescriptionEntry *vsdeHD = *avsdeHDsIt;
3770 ovf::DiskImagesMap::const_iterator itDiskImage = stack.mapDisks.find(vsdeHD->strRef);
3771 if (itDiskImage != stack.mapDisks.end())
3772 {
3773 const ovf::DiskImage &di = itDiskImage->second;
3774 d.uuid = Guid(di.uuidVBox);
3775 }
3776 ++avsdeHDsIt;
3777 }
3778
3779 // convert the Guid to string
3780 strUuid = d.uuid.toString();
3781
3782 if (diCurrent.uuidVBox != strUuid)
3783 {
3784 continue;
3785 }
3786
3787 /*
3788 * step 3: import disk
3789 */
3790 Utf8Str savedVBoxCurrent = vsdeTargetHD->strVBoxCurrent;
3791 ComObjPtr<Medium> pTargetHD;
3792
3793 i_importOneDiskImage(diCurrent,
3794 &vsdeTargetHD->strVBoxCurrent,
3795 pTargetHD,
3796 stack);
3797
3798 Bstr hdId;
3799
3800 ComObjPtr<MediumFormat> mediumFormat;
3801 rc = i_findMediumFormatFromDiskImage(diCurrent, mediumFormat);
3802 if (FAILED(rc))
3803 throw rc;
3804
3805 Bstr bstrFormatName;
3806 rc = mediumFormat->COMGETTER(Name)(bstrFormatName.asOutParam());
3807 if (FAILED(rc))
3808 throw rc;
3809
3810 Utf8Str vdf = Utf8Str(bstrFormatName);
3811
3812 if (vdf.compare("RAW", Utf8Str::CaseInsensitive) == 0)
3813 {
3814 ComPtr<IMedium> dvdImage(pTargetHD);
3815
3816 rc = mVirtualBox->OpenMedium(Bstr(vsdeTargetHD->strVBoxCurrent).raw(),
3817 DeviceType_DVD,
3818 AccessMode_ReadWrite,
3819 false,
3820 dvdImage.asOutParam());
3821
3822 if (FAILED(rc)) throw rc;
3823
3824 // ... and replace the old UUID in the machine config with the one of
3825 // the imported disk that was just created
3826 rc = dvdImage->COMGETTER(Id)(hdId.asOutParam());
3827 if (FAILED(rc)) throw rc;
3828 }
3829 else
3830 {
3831 // ... and replace the old UUID in the machine config with the one of
3832 // the imported disk that was just created
3833 rc = pTargetHD->COMGETTER(Id)(hdId.asOutParam());
3834 if (FAILED(rc)) throw rc;
3835 }
3836
3837 /* restore */
3838 vsdeTargetHD->strVBoxCurrent = savedVBoxCurrent;
3839
3840 /*
3841 * 1. saving original UUID for restoring in case of failure.
3842 * 2. replacement of original UUID by new UUID in the current VM config (settings::MachineConfigFile).
3843 */
3844 {
3845 rc = stack.saveOriginalUUIDOfAttachedDevice(d, Utf8Str(hdId));
3846 d.uuid = hdId;
3847 }
3848
3849 fFound = true;
3850 break;
3851 } // for (settings::AttachedDevicesList::const_iterator dit = sc.llAttachedDevices.begin();
3852 } // for (settings::StorageControllersList::const_iterator sit = config.storageMachine.llStorageControllers.begin();
3853
3854 // no disk with such a UUID found:
3855 if (!fFound)
3856 throw setError(E_FAIL,
3857 tr("<vbox:Machine> element in OVF contains a medium attachment for the disk image %s "
3858 "but the OVF describes no such image"),
3859 strUuid.c_str());
3860
3861 ++cImportedDisks;
3862
3863 }// while(oit != stack.mapDisks.end())
3864
3865
3866 /*
3867 * quantity of the imported disks isn't equal to the size of the avsdeHDs list.
3868 */
3869 if(cImportedDisks < avsdeHDs.size())
3870 {
3871 Log1Warning(("Not all disk images were imported for VM %s. Check OVF description file.",
3872 vmNameEntry->strOvf.c_str()));
3873 }
3874
3875 /*
3876 * step 4): create the machine and have it import the config
3877 */
3878
3879 ComObjPtr<Machine> pNewMachine;
3880 rc = pNewMachine.createObject();
3881 if (FAILED(rc)) throw rc;
3882
3883 // this magic constructor fills the new machine object with the MachineConfig
3884 // instance that we created from the vbox:Machine
3885 rc = pNewMachine->init(mVirtualBox,
3886 stack.strNameVBox,// name from OVF preparations; can be suffixed to avoid duplicates
3887 config); // the whole machine config
3888 if (FAILED(rc)) throw rc;
3889
3890 pReturnNewMachine = ComPtr<IMachine>(pNewMachine);
3891
3892 // and register it
3893 rc = mVirtualBox->RegisterMachine(pNewMachine);
3894 if (FAILED(rc)) throw rc;
3895
3896 // store new machine for roll-back in case of errors
3897 Bstr bstrNewMachineId;
3898 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
3899 if (FAILED(rc)) throw rc;
3900 m->llGuidsMachinesCreated.push_back(Guid(bstrNewMachineId));
3901
3902 LogFlowFuncLeave();
3903}
3904
3905/**
3906 * @throws HRESULT errors.
3907 */
3908void Appliance::i_importMachines(ImportStack &stack)
3909{
3910 // this is safe to access because this thread only gets started
3911 const ovf::OVFReader &reader = *m->pReader;
3912
3913 // create a session for the machine + disks we manipulate below
3914 HRESULT rc = stack.pSession.createInprocObject(CLSID_Session);
3915 ComAssertComRCThrowRC(rc);
3916
3917 list<ovf::VirtualSystem>::const_iterator it;
3918 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it1;
3919 /* Iterate through all virtual systems of that appliance */
3920 size_t i = 0;
3921 for (it = reader.m_llVirtualSystems.begin(), it1 = m->virtualSystemDescriptions.begin();
3922 it != reader.m_llVirtualSystems.end() && it1 != m->virtualSystemDescriptions.end();
3923 ++it, ++it1, ++i)
3924 {
3925 const ovf::VirtualSystem &vsysThis = *it;
3926 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it1);
3927
3928 ComPtr<IMachine> pNewMachine;
3929
3930 // there are two ways in which we can create a vbox machine from OVF:
3931 // -- either this OVF was written by vbox 3.2 or later, in which case there is a <vbox:Machine> element
3932 // in the <VirtualSystem>; then the VirtualSystemDescription::Data has a settings::MachineConfigFile
3933 // with all the machine config pretty-parsed;
3934 // -- or this is an OVF from an older vbox or an external source, and then we need to translate the
3935 // VirtualSystemDescriptionEntry and do import work
3936
3937 // Even for the vbox:Machine case, there are a number of configuration items that will be taken from
3938 // the OVF because otherwise the "override import parameters" mechanism in the GUI won't work.
3939
3940 // VM name
3941 std::list<VirtualSystemDescriptionEntry*> vsdeName = vsdescThis->i_findByType(VirtualSystemDescriptionType_Name);
3942 if (vsdeName.size() < 1)
3943 throw setError(VBOX_E_FILE_ERROR,
3944 tr("Missing VM name"));
3945 stack.strNameVBox = vsdeName.front()->strVBoxCurrent;
3946
3947 // have VirtualBox suggest where the filename would be placed so we can
3948 // put the disk images in the same directory
3949 Bstr bstrMachineFilename;
3950 rc = mVirtualBox->ComposeMachineFilename(Bstr(stack.strNameVBox).raw(),
3951 NULL /* aGroup */,
3952 NULL /* aCreateFlags */,
3953 NULL /* aBaseFolder */,
3954 bstrMachineFilename.asOutParam());
3955 if (FAILED(rc)) throw rc;
3956 // and determine the machine folder from that
3957 stack.strMachineFolder = bstrMachineFilename;
3958 stack.strMachineFolder.stripFilename();
3959 LogFunc(("i=%zu strName=%s bstrMachineFilename=%ls\n", i, stack.strNameVBox.c_str(), bstrMachineFilename.raw()));
3960
3961 // guest OS type
3962 std::list<VirtualSystemDescriptionEntry*> vsdeOS;
3963 vsdeOS = vsdescThis->i_findByType(VirtualSystemDescriptionType_OS);
3964 if (vsdeOS.size() < 1)
3965 throw setError(VBOX_E_FILE_ERROR,
3966 tr("Missing guest OS type"));
3967 stack.strOsTypeVBox = vsdeOS.front()->strVBoxCurrent;
3968
3969 // CPU count
3970 std::list<VirtualSystemDescriptionEntry*> vsdeCPU = vsdescThis->i_findByType(VirtualSystemDescriptionType_CPU);
3971 if (vsdeCPU.size() != 1)
3972 throw setError(VBOX_E_FILE_ERROR, tr("CPU count missing"));
3973
3974 stack.cCPUs = vsdeCPU.front()->strVBoxCurrent.toUInt32();
3975 // We need HWVirt & IO-APIC if more than one CPU is requested
3976 if (stack.cCPUs > 1)
3977 {
3978 stack.fForceHWVirt = true;
3979 stack.fForceIOAPIC = true;
3980 }
3981
3982 // RAM
3983 std::list<VirtualSystemDescriptionEntry*> vsdeRAM = vsdescThis->i_findByType(VirtualSystemDescriptionType_Memory);
3984 if (vsdeRAM.size() != 1)
3985 throw setError(VBOX_E_FILE_ERROR, tr("RAM size missing"));
3986 stack.ulMemorySizeMB = (ULONG)vsdeRAM.front()->strVBoxCurrent.toUInt64();
3987
3988#ifdef VBOX_WITH_USB
3989 // USB controller
3990 std::list<VirtualSystemDescriptionEntry*> vsdeUSBController =
3991 vsdescThis->i_findByType(VirtualSystemDescriptionType_USBController);
3992 // USB support is enabled if there's at least one such entry; to disable USB support,
3993 // the type of the USB item would have been changed to "ignore"
3994 stack.fUSBEnabled = !vsdeUSBController.empty();
3995#endif
3996 // audio adapter
3997 std::list<VirtualSystemDescriptionEntry*> vsdeAudioAdapter =
3998 vsdescThis->i_findByType(VirtualSystemDescriptionType_SoundCard);
3999 /* @todo: we support one audio adapter only */
4000 if (!vsdeAudioAdapter.empty())
4001 stack.strAudioAdapter = vsdeAudioAdapter.front()->strVBoxCurrent;
4002
4003 // for the description of the new machine, always use the OVF entry, the user may have changed it in the import config
4004 std::list<VirtualSystemDescriptionEntry*> vsdeDescription =
4005 vsdescThis->i_findByType(VirtualSystemDescriptionType_Description);
4006 if (!vsdeDescription.empty())
4007 stack.strDescription = vsdeDescription.front()->strVBoxCurrent;
4008
4009 // import vbox:machine or OVF now
4010 if (vsdescThis->m->pConfig)
4011 // vbox:Machine config
4012 i_importVBoxMachine(vsdescThis, pNewMachine, stack);
4013 else
4014 // generic OVF config
4015 i_importMachineGeneric(vsysThis, vsdescThis, pNewMachine, stack);
4016
4017 } // for (it = pAppliance->m->llVirtualSystems.begin() ...
4018}
4019
4020HRESULT Appliance::ImportStack::saveOriginalUUIDOfAttachedDevice(settings::AttachedDevice &device,
4021 const Utf8Str &newlyUuid)
4022{
4023 HRESULT rc = S_OK;
4024
4025 /* save for restoring */
4026 mapNewUUIDsToOriginalUUIDs.insert(std::make_pair(newlyUuid, device.uuid.toString()));
4027
4028 return rc;
4029}
4030
4031HRESULT Appliance::ImportStack::restoreOriginalUUIDOfAttachedDevice(settings::MachineConfigFile *config)
4032{
4033 HRESULT rc = S_OK;
4034
4035 settings::StorageControllersList &llControllers = config->storageMachine.llStorageControllers;
4036 settings::StorageControllersList::iterator itscl;
4037 for (itscl = llControllers.begin();
4038 itscl != llControllers.end();
4039 ++itscl)
4040 {
4041 settings::AttachedDevicesList &llAttachments = itscl->llAttachedDevices;
4042 settings::AttachedDevicesList::iterator itadl = llAttachments.begin();
4043 while (itadl != llAttachments.end())
4044 {
4045 std::map<Utf8Str , Utf8Str>::iterator it =
4046 mapNewUUIDsToOriginalUUIDs.find(itadl->uuid.toString());
4047 if(it!=mapNewUUIDsToOriginalUUIDs.end())
4048 {
4049 Utf8Str uuidOriginal = it->second;
4050 itadl->uuid = Guid(uuidOriginal);
4051 mapNewUUIDsToOriginalUUIDs.erase(it->first);
4052 }
4053 ++itadl;
4054 }
4055 }
4056
4057 return rc;
4058}
4059
4060/**
4061 * @throws Nothing
4062 */
4063RTVFSIOSTREAM Appliance::ImportStack::claimOvaLookAHead(void)
4064{
4065 RTVFSIOSTREAM hVfsIos = this->hVfsIosOvaLookAhead;
4066 this->hVfsIosOvaLookAhead = NIL_RTVFSIOSTREAM;
4067 /* We don't free the name since it may be referenced in error messages and such. */
4068 return hVfsIos;
4069}
4070
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