VirtualBox

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

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

ApplianceImplImport.cpp: Use RTCrPemFindFirstSectionInContent.

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