VirtualBox

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

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

ApplianceImpl: Only warn if we cannot root a certificate (compare self-signed and neighbours).

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