VirtualBox

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

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

ApplianceImplImport.cpp: Simplifications.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 159.7 KB
Line 
1/* $Id: ApplianceImplImport.cpp 59582 2016-02-04 15:01:22Z vboxsync $ */
2/** @file
3 * IAppliance and IVirtualSystem COM class implementations.
4 */
5
6/*
7 * Copyright (C) 2008-2015 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/path.h>
19#include <iprt/dir.h>
20#include <iprt/file.h>
21#include <iprt/s3.h>
22#include <iprt/sha.h>
23#include <iprt/manifest.h>
24#include <iprt/tar.h>
25#include <iprt/stream.h>
26
27#include <VBox/vd.h>
28#include <VBox/com/array.h>
29
30#include "ApplianceImpl.h"
31#include "VirtualBoxImpl.h"
32#include "GuestOSTypeImpl.h"
33#include "ProgressImpl.h"
34#include "MachineImpl.h"
35#include "MediumImpl.h"
36#include "MediumFormatImpl.h"
37#include "SystemPropertiesImpl.h"
38#include "HostImpl.h"
39
40#include "AutoCaller.h"
41#include "Logging.h"
42
43#include "ApplianceImplPrivate.h"
44
45#include <VBox/param.h>
46#include <VBox/version.h>
47#include <VBox/settings.h>
48
49#include <iprt/x509-branch-collision.h>
50#include <set>
51
52using namespace std;
53
54////////////////////////////////////////////////////////////////////////////////
55//
56// IAppliance public methods
57//
58////////////////////////////////////////////////////////////////////////////////
59
60/**
61 * Public method implementation. This opens the OVF with ovfreader.cpp.
62 * Thread implementation is in Appliance::readImpl().
63 *
64 * @param aFile
65 * @return
66 */
67HRESULT Appliance::read(const com::Utf8Str &aFile,
68 ComPtr<IProgress> &aProgress)
69{
70 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
71
72 if (!i_isApplianceIdle())
73 return E_ACCESSDENIED;
74
75 if (m->pReader)
76 {
77 delete m->pReader;
78 m->pReader = NULL;
79 }
80
81 // see if we can handle this file; for now we insist it has an ovf/ova extension
82 if (!( aFile.endsWith(".ovf", Utf8Str::CaseInsensitive)
83 || aFile.endsWith(".ova", Utf8Str::CaseInsensitive)))
84 return setError(VBOX_E_FILE_ERROR,
85 tr("Appliance file must have .ovf extension"));
86
87 ComObjPtr<Progress> progress;
88 HRESULT rc = S_OK;
89 try
90 {
91 /* Parse all necessary info out of the URI */
92 i_parseURI(aFile, m->locInfo);
93 rc = i_readImpl(m->locInfo, progress);
94 }
95 catch (HRESULT aRC)
96 {
97 rc = aRC;
98 }
99
100 if (SUCCEEDED(rc))
101 /* Return progress to the caller */
102 progress.queryInterfaceTo(aProgress.asOutParam());
103
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
770 (ImportOptions_KeepAllMACs)
771 && m->optListImport.contains(ImportOptions_KeepNATMACs)
772 ), E_INVALIDARG);
773
774 // do not allow entering this method if the appliance is busy reading or writing
775 if (!i_isApplianceIdle())
776 return E_ACCESSDENIED;
777
778 if (!m->pReader)
779 return setError(E_FAIL,
780 tr("Cannot import machines without reading it first (call read() before i_importMachines())"));
781
782 ComObjPtr<Progress> progress;
783 HRESULT rc = S_OK;
784 try
785 {
786 rc = i_importImpl(m->locInfo, progress);
787 }
788 catch (HRESULT aRC)
789 {
790 rc = aRC;
791 }
792
793 if (SUCCEEDED(rc))
794 /* Return progress to the caller */
795 progress.queryInterfaceTo(aProgress.asOutParam());
796
797 return rc;
798}
799
800////////////////////////////////////////////////////////////////////////////////
801//
802// Appliance private methods
803//
804////////////////////////////////////////////////////////////////////////////////
805
806HRESULT Appliance::i_preCheckImageAvailability(PSHASTORAGE pSHAStorage,
807 RTCString &availableImage)
808{
809 PFSSRDONLYINTERFACEIO pTarIo = (PFSSRDONLYINTERFACEIO)pSHAStorage->pVDImageIfaces->pvUser;
810 const char *pszFilename;
811 int vrc = fssRdOnlyGetCurrentName(pTarIo, &pszFilename);
812 if (RT_SUCCESS(vrc))
813 {
814 if (!fssRdOnlyIsCurrentDirectory(pTarIo))
815 {
816 availableImage = pszFilename;
817 return S_OK;
818 }
819
820 throw setError(VBOX_E_FILE_ERROR, tr("Empty directory folder (%s) isn't allowed in the OVA package (%Rrc)"),
821 pszFilename, VERR_IS_A_DIRECTORY);
822 }
823
824 throw setError(VBOX_E_FILE_ERROR, tr("Could not open the current file in the OVA package (%Rrc)"), vrc);
825}
826
827/*******************************************************************************
828 * Read stuff
829 ******************************************************************************/
830
831/**
832 * Implementation for reading an OVF (via task).
833 *
834 * This starts a new thread which will call
835 * Appliance::taskThreadImportOrExport() which will then call readFS(). This
836 * will then open the OVF with ovfreader.cpp.
837 *
838 * This is in a separate private method because it is used from two locations:
839 *
840 * 1) from the public Appliance::Read().
841 *
842 * 2) in a second worker thread; in that case, Appliance::ImportMachines() called Appliance::i_importImpl(), which
843 * called Appliance::readFSOVA(), which called Appliance::i_importImpl(), which then called this again.
844 *
845 * @param aLocInfo The OVF location.
846 * @param aProgress Where to return the progress object.
847 * @return COM success status code. COM error codes will be thrown.
848 */
849HRESULT Appliance::i_readImpl(const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
850{
851 BstrFmt bstrDesc = BstrFmt(tr("Reading appliance '%s'"),
852 aLocInfo.strPath.c_str());
853 HRESULT rc;
854 /* Create the progress object */
855 aProgress.createObject();
856 if (aLocInfo.storageType == VFSType_File)
857 /* 1 operation only */
858 rc = aProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
859 bstrDesc.raw(),
860 TRUE /* aCancelable */);
861 else
862 /* 4/5 is downloading, 1/5 is reading */
863 rc = aProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
864 bstrDesc.raw(),
865 TRUE /* aCancelable */,
866 2, // ULONG cOperations,
867 5, // ULONG ulTotalOperationsWeight,
868 BstrFmt(tr("Download appliance '%s'"),
869 aLocInfo.strPath.c_str()).raw(), // CBSTR bstrFirstOperationDescription,
870 4); // ULONG ulFirstOperationWeight,
871 if (FAILED(rc)) throw rc;
872
873 /* Initialize our worker task */
874 TaskOVF* task = NULL;
875 try
876 {
877 task = new TaskOVF(this, TaskOVF::Read, aLocInfo, aProgress);
878 }
879 catch(...)
880 {
881 delete task;
882 throw rc = setError(VBOX_E_OBJECT_NOT_FOUND,
883 tr("Could not create TaskOVF object for reading the OVF from disk"));
884 }
885
886 rc = task->createThread();
887 if (FAILED(rc)) throw rc;
888
889 return rc;
890}
891
892/**
893 * Actual worker code for reading an OVF from disk. This is called from Appliance::taskThreadImportOrExport()
894 * and therefore runs on the OVF read worker thread. This opens the OVF with ovfreader.cpp.
895 *
896 * This runs in one context:
897 *
898 * 1) in a first worker thread; in that case, Appliance::Read() called Appliance::readImpl();
899 *
900 * @param pTask
901 * @return
902 */
903HRESULT Appliance::i_readFS(TaskOVF *pTask)
904{
905 LogFlowFuncEnter();
906 LogFlowFunc(("Appliance %p\n", this));
907
908 AutoCaller autoCaller(this);
909 if (FAILED(autoCaller.rc())) return autoCaller.rc();
910
911 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
912
913 HRESULT rc = S_OK;
914
915 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
916 rc = i_readFSOVF(pTask);
917 else
918 rc = i_readFSOVA(pTask);
919
920 LogFlowFunc(("rc=%Rhrc\n", rc));
921 LogFlowFuncLeave();
922
923 return rc;
924}
925
926HRESULT Appliance::i_readFSOVF(TaskOVF *pTask)
927{
928 LogFlowFuncEnter();
929
930 HRESULT rc = S_OK;
931 int vrc = VINF_SUCCESS;
932
933 PVDINTERFACEIO pShaIo = 0;
934 PVDINTERFACEIO pFileIo = 0;
935 RTMANIFEST hOvfManifest = NIL_RTMANIFEST;
936
937 do
938 {
939 try
940 {
941 /* Create the necessary file access interfaces. */
942 pFileIo = FileCreateInterface();
943 AssertBreakStmt(pFileIo, rc = E_OUTOFMEMORY);
944
945 Utf8Str strMfFile = Utf8Str(pTask->locInfo.strPath).stripSuffix().append(".mf");
946
947 SHASTORAGE storage;
948 RT_ZERO(storage);
949
950 /* Check and read the manifest file to determine the digests we need to calculate. */
951 uint32_t fTypes = 0;
952 if (RTFileExists(strMfFile.c_str()))
953 {
954 vrc = RTManifestCreate(0 /*fFlags*/, &hOvfManifest);
955 AssertBreakStmt(RT_SUCCESS(vrc), rc = E_OUTOFMEMORY);
956
957 RTVFSFILE hManifestVfsFile;
958 vrc = RTVfsFileOpenNormal(strMfFile.c_str(),
959 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE, &hManifestVfsFile);
960 if (RT_FAILURE(vrc))
961 throw setError(VBOX_E_FILE_ERROR,
962 tr("Could not open the manifest file '%s' (%Rrc)"), strMfFile.c_str(), vrc);
963 char szErr[256];
964 RTVFSIOSTREAM hVfsIosTmp = RTVfsFileToIoStream(hManifestVfsFile);
965 vrc = RTManifestReadStandardEx(hOvfManifest, hVfsIosTmp, szErr, sizeof(szErr));
966 RTVfsIoStrmRelease(hVfsIosTmp);
967 RTVfsFileRelease(hManifestVfsFile);
968 if (RT_FAILURE(vrc))
969 throw setErrorVrc(vrc, tr("Failed to read or parse manifest file '%s' (%Rrc): %s"),
970 strMfFile.c_str(), vrc, szErr);
971
972 vrc = RTManifestQueryAllAttrTypes(hOvfManifest, true /*fEntriesOnly*/, &fTypes);
973 AssertRCBreakStmt(vrc, rc = Global::vboxStatusCodeToCOM(vrc));
974 }
975
976 /* If any digests was found, we must wrap the I/O interface with a SHA calculator. */
977 if (fTypes)
978 {
979 pShaIo = ShaCreateInterface();
980 AssertBreakStmt(pShaIo, rc = E_OUTOFMEMORY);
981
982 storage.fCreateDigest = true;
983
984 Assert(RT_IS_POWER_OF_TWO(fTypes)); /** @todo support anything and mixed (easy when supporting SHA256 for OVA < v2.0). */
985 if (fTypes & RTMANIFEST_ATTR_SHA256)
986 storage.fSha256 = true;
987
988 Utf8Str name = i_applianceIOName(applianceIOFile);
989
990 vrc = VDInterfaceAdd(&pFileIo->Core, name.c_str(),
991 VDINTERFACETYPE_IO, 0, sizeof(VDINTERFACEIO),
992 &storage.pVDImageIfaces);
993 if (RT_FAILURE(vrc))
994 throw setError(VBOX_E_IPRT_ERROR, "Creation of the VD interface failed (%Rrc)", vrc);
995
996 rc = i_readFSImpl(pTask, pTask->locInfo.strPath, pShaIo, &storage);
997 if (FAILED(rc))
998 break;
999 }
1000 else
1001 {
1002 storage.fCreateDigest = false;
1003 rc = i_readFSImpl(pTask, pTask->locInfo.strPath, pFileIo, &storage);
1004 if (FAILED(rc))
1005 break;
1006 }
1007 }
1008 catch (HRESULT rc2)
1009 {
1010 rc = rc2;
1011 }
1012
1013 } while (0);
1014
1015 /* Cleanup */
1016 if (pShaIo)
1017 RTMemFree(pShaIo);
1018 if (pFileIo)
1019 RTMemFree(pFileIo);
1020 if (hOvfManifest != NIL_RTMANIFEST)
1021 RTManifestRelease(hOvfManifest);
1022
1023 LogFlowFunc(("rc=%Rhrc\n", rc));
1024 LogFlowFuncLeave();
1025
1026 return rc;
1027}
1028
1029HRESULT Appliance::i_readFSOVA(TaskOVF *pTask)
1030{
1031 LogFlowFuncEnter();
1032
1033 /*
1034 * Open the tar file and get a VD I/O interface for it.
1035 */
1036 HRESULT hrc;
1037 PFSSRDONLYINTERFACEIO pTarIo;
1038 int vrc = fssRdOnlyCreateInterfaceForTarFile(pTask->locInfo.strPath.c_str(), &pTarIo);
1039 if (RT_SUCCESS(vrc))
1040 {
1041 /*
1042 * Check that the first file is has an .ovf suffix.
1043 */
1044 const char *pszName;
1045 vrc = fssRdOnlyGetCurrentName(pTarIo, &pszName);
1046 if (RT_SUCCESS(vrc))
1047 {
1048 size_t cchName = strlen(pszName);
1049 if ( cchName >= sizeof(".ovf")
1050 && RTStrICmp(&pszName[cchName - sizeof(".ovf") + 1], ".ovf") == 0)
1051 {
1052 /*
1053 * Stack the rest of the expected VD I/O stuff.
1054 */
1055 PVDINTERFACEIO pShaIo = ShaCreateInterface();
1056 if (pShaIo)
1057 {
1058 Utf8Str IoName = i_applianceIOName(applianceIOTar);
1059 SHASTORAGE ShaStorage;
1060 RT_ZERO(ShaStorage);
1061 vrc = VDInterfaceAdd((PVDINTERFACE)pTarIo, IoName.c_str(),
1062 VDINTERFACETYPE_IO, pTarIo, sizeof(VDINTERFACEIO),
1063 &ShaStorage.pVDImageIfaces);
1064 if (RT_SUCCESS(vrc))
1065 /*
1066 * Read and parse the OVF.
1067 */
1068 hrc = i_readFSImpl(pTask, pszName, pShaIo, &ShaStorage);
1069 else
1070 hrc = setError(VBOX_E_IPRT_ERROR, "Creation of the VD interface failed (%Rrc)", vrc);
1071 RTMemFree(pShaIo);
1072 }
1073 else
1074 hrc = E_OUTOFMEMORY;
1075 }
1076 else
1077 hrc = setError(VBOX_E_FILE_ERROR,
1078 tr("First file in the OVA package must have the extension 'ovf'. But the file '%s' has a different extension."),
1079 pszName);
1080 }
1081 else
1082 hrc = setError(VBOX_E_FILE_ERROR, tr("Error reading OVA file '%s' (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
1083 fssRdOnlyDestroyInterface(pTarIo);
1084 }
1085 else
1086 hrc = setError(VBOX_E_FILE_ERROR, tr("Could not open the OVA file '%s' (%Rrc)"), pTask->locInfo.strPath.c_str(), vrc);
1087
1088 LogFlowFunc(("rc=%Rhrc\n", hrc));
1089 LogFlowFuncLeave();
1090 return hrc;
1091}
1092
1093HRESULT Appliance::i_readFSImpl(TaskOVF *pTask, const RTCString &strFilename, PVDINTERFACEIO pIfIo, PSHASTORAGE pStorage)
1094{
1095 LogFlowFuncEnter();
1096
1097 HRESULT rc = S_OK;
1098
1099 pStorage->fCreateDigest = true;
1100
1101 void *pvTmpBuf = 0;
1102 try
1103 {
1104 /* Read the OVF into a memory buffer */
1105 size_t cbSize = 0;
1106 int vrc = readFileIntoBuffer(strFilename.c_str(), &pvTmpBuf, &cbSize, pIfIo, pStorage);
1107 if (RT_FAILURE(vrc)
1108 || !pvTmpBuf)
1109 throw setError(VBOX_E_FILE_ERROR,
1110 tr("Could not read OVF file '%s' (%Rrc)"),
1111 RTPathFilename(strFilename.c_str()), vrc);
1112
1113 /* Read & parse the XML structure of the OVF file */
1114 m->pReader = new ovf::OVFReader(pvTmpBuf, cbSize, pTask->locInfo.strPath);
1115
1116 if ( pStorage->fSha256
1117 || m->pReader->m_envelopeData.getOVFVersion() == ovf::OVFVersion_2_0)
1118 {
1119 m->fSha256 = true;
1120
1121 /* Calc the SHA256 sum of the OVF file for later validation */
1122 uint8_t abHash[RTSHA256_HASH_SIZE];
1123 RTSha256(pvTmpBuf, cbSize, abHash);
1124
1125 char szDigest[RTSHA256_DIGEST_LEN + 1];
1126 vrc = RTSha256ToString(abHash, szDigest, sizeof(szDigest));
1127 AssertStmt(RT_SUCCESS(vrc), throw VBOX_E_IPRT_ERROR);
1128
1129 m->strOVFSHADigest = szDigest;
1130 }
1131 else
1132 {
1133 m->fSha256 = false;
1134 /* Copy the SHA1 sum of the OVF file for later validation */
1135 m->strOVFSHADigest = pStorage->strDigest;
1136 }
1137
1138 }
1139 catch (RTCError &x) // includes all XML exceptions
1140 {
1141 rc = setError(VBOX_E_FILE_ERROR,
1142 x.what());
1143 }
1144 catch (HRESULT aRC)
1145 {
1146 rc = aRC;
1147 }
1148
1149 /* Cleanup */
1150 if (pvTmpBuf)
1151 RTMemFree(pvTmpBuf);
1152
1153 LogFlowFunc(("rc=%Rhrc\n", rc));
1154 LogFlowFuncLeave();
1155
1156 return rc;
1157}
1158
1159
1160/*******************************************************************************
1161 * Import stuff
1162 ******************************************************************************/
1163
1164/**
1165 * Implementation for importing OVF data into VirtualBox. This starts a new thread which will call
1166 * Appliance::taskThreadImportOrExport().
1167 *
1168 * This creates one or more new machines according to the VirtualSystemScription instances created by
1169 * Appliance::Interpret().
1170 *
1171 * This is in a separate private method because it is used from one location:
1172 *
1173 * 1) from the public Appliance::ImportMachines().
1174 *
1175 * @param aLocInfo
1176 * @param aProgress
1177 * @return
1178 */
1179HRESULT Appliance::i_importImpl(const LocationInfo &locInfo,
1180 ComObjPtr<Progress> &progress)
1181{
1182 HRESULT rc = S_OK;
1183
1184 SetUpProgressMode mode;
1185 if (locInfo.storageType == VFSType_File)
1186 mode = ImportFile;
1187 else
1188 mode = ImportS3;
1189
1190 rc = i_setUpProgress(progress,
1191 BstrFmt(tr("Importing appliance '%s'"), locInfo.strPath.c_str()),
1192 mode);
1193 if (FAILED(rc)) throw rc;
1194
1195 /* Initialize our worker task */
1196 TaskOVF* task = NULL;
1197 try
1198 {
1199 task = new TaskOVF(this, TaskOVF::Import, locInfo, progress);
1200 }
1201 catch(...)
1202 {
1203 delete task;
1204 throw rc = setError(VBOX_E_OBJECT_NOT_FOUND,
1205 tr("Could not create TaskOVF object for importing OVF data into VirtualBox"));
1206 }
1207
1208 rc = task->createThread();
1209 if (FAILED(rc)) throw rc;
1210
1211 return rc;
1212}
1213
1214/**
1215 * Actual worker code for importing OVF data into VirtualBox.
1216 *
1217 * This is called from Appliance::taskThreadImportOrExport() and therefore runs
1218 * on the OVF import worker thread. This creates one or more new machines
1219 * according to the VirtualSystemScription instances created by
1220 * Appliance::Interpret().
1221 *
1222 * This runs in two contexts:
1223 *
1224 * 1) in a first worker thread; in that case, Appliance::ImportMachines() called Appliance::i_importImpl();
1225 *
1226 * 2) in a second worker thread; in that case, Appliance::ImportMachines() called Appliance::i_importImpl(), which
1227 * called Appliance::i_i_importFSOVA(), which called Appliance::i_importImpl(), which then called this again.
1228 *
1229 * @param pTask The OVF task data.
1230 * @return COM status code.
1231 */
1232HRESULT Appliance::i_importFS(TaskOVF *pTask)
1233{
1234
1235 LogFlowFuncEnter();
1236 LogFlowFunc(("Appliance %p\n", this));
1237
1238 /* Change the appliance state so we can safely leave the lock while doing
1239 * time-consuming disk imports; also the below method calls do all kinds of
1240 * locking which conflicts with the appliance object lock. */
1241 AutoWriteLock writeLock(this COMMA_LOCKVAL_SRC_POS);
1242 /* Check if the appliance is currently busy. */
1243 if (!i_isApplianceIdle())
1244 return E_ACCESSDENIED;
1245 /* Set the internal state to importing. */
1246 m->state = Data::ApplianceImporting;
1247
1248 HRESULT rc = S_OK;
1249
1250 /* Clear the list of imported machines, if any */
1251 m->llGuidsMachinesCreated.clear();
1252
1253 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
1254 rc = i_importFSOVF(pTask, writeLock);
1255 else
1256 rc = i_importFSOVA(pTask, writeLock);
1257
1258 if (FAILED(rc))
1259 {
1260 /* With _whatever_ error we've had, do a complete roll-back of
1261 * machines and disks we've created */
1262 writeLock.release();
1263 ErrorInfoKeeper eik;
1264 for (list<Guid>::iterator itID = m->llGuidsMachinesCreated.begin();
1265 itID != m->llGuidsMachinesCreated.end();
1266 ++itID)
1267 {
1268 Guid guid = *itID;
1269 Bstr bstrGuid = guid.toUtf16();
1270 ComPtr<IMachine> failedMachine;
1271 HRESULT rc2 = mVirtualBox->FindMachine(bstrGuid.raw(), failedMachine.asOutParam());
1272 if (SUCCEEDED(rc2))
1273 {
1274 SafeIfaceArray<IMedium> aMedia;
1275 rc2 = failedMachine->Unregister(CleanupMode_DetachAllReturnHardDisksOnly, ComSafeArrayAsOutParam(aMedia));
1276 ComPtr<IProgress> pProgress2;
1277 rc2 = failedMachine->DeleteConfig(ComSafeArrayAsInParam(aMedia), pProgress2.asOutParam());
1278 pProgress2->WaitForCompletion(-1);
1279 }
1280 }
1281 writeLock.acquire();
1282 }
1283
1284 /* Reset the state so others can call methods again */
1285 m->state = Data::ApplianceIdle;
1286
1287 LogFlowFunc(("rc=%Rhrc\n", rc));
1288 LogFlowFuncLeave();
1289
1290 return rc;
1291}
1292
1293HRESULT Appliance::i_importFSOVF(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1294{
1295 LogFlowFuncEnter();
1296
1297 HRESULT rc = S_OK;
1298
1299 PVDINTERFACEIO pShaIo = NULL;
1300 PVDINTERFACEIO pFileIo = NULL;
1301 RTVFSFILE hManifestVfsFile = NIL_RTVFSFILE;
1302 void *pvCertBuf = NULL;
1303 writeLock.release();
1304
1305 /* Create the import stack for the rollback on errors. */
1306 ImportStack stack(pTask->locInfo, m->pReader->m_mapDisks, pTask->pProgress);
1307 try
1308 {
1309 int vrc = RTManifestCreate(0 /*fFlags*/, &stack.hSrcDisksManifest);
1310 if (RT_FAILURE(vrc))
1311 throw setError(E_OUTOFMEMORY);
1312
1313 /* Create the necessary file access interfaces. */
1314 pFileIo = FileCreateInterface();
1315 if (!pFileIo)
1316 throw setError(E_OUTOFMEMORY);
1317
1318 Utf8Str strMfFile = Utf8Str(pTask->locInfo.strPath).stripSuffix().append(".mf");
1319
1320 SHASTORAGE storage;
1321 RT_ZERO(storage);
1322
1323 Utf8Str name = i_applianceIOName(applianceIOFile);
1324
1325 vrc = VDInterfaceAdd(&pFileIo->Core, name.c_str(),
1326 VDINTERFACETYPE_IO, 0, sizeof(VDINTERFACEIO),
1327 &storage.pVDImageIfaces);
1328 if (RT_FAILURE(vrc))
1329 throw setError(VBOX_E_IPRT_ERROR, "Creation of the VD interface failed (%Rrc)", vrc);
1330
1331 if (RTFileExists(strMfFile.c_str()))
1332 {
1333 pShaIo = ShaCreateInterface();
1334 if (!pShaIo)
1335 throw setError(E_OUTOFMEMORY);
1336
1337 Utf8Str nameSha = i_applianceIOName(applianceIOSha);
1338 /* Fill out interface descriptor. */
1339 pShaIo->Core.u32Magic = VDINTERFACE_MAGIC;
1340 pShaIo->Core.cbSize = sizeof(VDINTERFACEIO);
1341 pShaIo->Core.pszInterfaceName = nameSha.c_str();
1342 pShaIo->Core.enmInterface = VDINTERFACETYPE_IO;
1343 pShaIo->Core.pvUser = &storage;
1344 pShaIo->Core.pNext = NULL;
1345
1346 storage.fCreateDigest = true;
1347
1348 /* Now import the appliance. */
1349 i_importMachines(stack, pShaIo, &storage);
1350
1351 /* Add the digest of the ovf to our verification manifest. */
1352 vrc = RTManifestEntrySetAttr(stack.hSrcDisksManifest, RTPathFilename(pTask->locInfo.strPath.c_str()),
1353 NULL /*pszAttr*/, m->strOVFSHADigest.c_str(),
1354 m->fSha256 ? RTMANIFEST_ATTR_SHA256 : RTMANIFEST_ATTR_SHA1);
1355 if (RT_FAILURE(vrc))
1356 throw setError(VBOX_E_IPRT_ERROR, "Adding OVF digest failed (%Rrc)", vrc);
1357
1358 /* Read & verify the manifest file. */
1359 vrc = RTVfsFileOpenNormal(strMfFile.c_str(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE, &hManifestVfsFile);
1360 if (RT_SUCCESS(vrc))
1361 {
1362 rc = i_verifyManifestFile(strMfFile, stack, hManifestVfsFile, RTPathFilename(pTask->locInfo.strPath.c_str()));
1363 if (FAILED(rc)) throw rc;
1364 }
1365 else if (vrc != VERR_FILE_NOT_FOUND)
1366 throw setError(VBOX_E_IPRT_ERROR, tr("Error opening manifest file '%s' (%Rrc)"), strMfFile.c_str(), vrc);
1367
1368 size_t cbCertFile = 0;
1369
1370 /* Save the SHA digest of the manifest file for the next validation */
1371 Utf8Str manifestShaDigest = storage.strDigest;
1372
1373 Utf8Str strCertFile = Utf8Str(pTask->locInfo.strPath).stripSuffix().append(".cert");
1374 if (RTFileExists(strCertFile.c_str()))
1375 {
1376 rc = i_readFileToBuf(strCertFile, &pvCertBuf, &cbCertFile, false, pShaIo, &storage);
1377 if (FAILED(rc)) throw rc;
1378
1379 /* verify Certificate */
1380 rc = i_verifyCertificateFile(pvCertBuf, cbCertFile, &storage);
1381 if (FAILED(rc)) throw rc;
1382 }
1383 }
1384 else
1385 {
1386 storage.fCreateDigest = false;
1387 i_importMachines(stack, pFileIo, &storage);
1388 }
1389 }
1390 catch (HRESULT rc2)
1391 {
1392 rc = rc2;
1393 /*
1394 * Restoring original UUID from OVF description file.
1395 * During import VBox creates new UUIDs for imported images and
1396 * assigns them to the images. In case of failure we have to restore
1397 * the original UUIDs because those new UUIDs are obsolete now and
1398 * won't be used anymore.
1399 */
1400 {
1401 ErrorInfoKeeper eik; /* paranoia */
1402 list< ComObjPtr<VirtualSystemDescription> >::const_iterator itvsd;
1403 /* Iterate through all virtual systems of that appliance */
1404 for (itvsd = m->virtualSystemDescriptions.begin();
1405 itvsd != m->virtualSystemDescriptions.end();
1406 ++itvsd)
1407 {
1408 ComObjPtr<VirtualSystemDescription> vsdescThis = (*itvsd);
1409 settings::MachineConfigFile *pConfig = vsdescThis->m->pConfig;
1410 if(vsdescThis->m->pConfig!=NULL)
1411 stack.restoreOriginalUUIDOfAttachedDevice(pConfig);
1412 }
1413 }
1414 }
1415 writeLock.acquire();
1416
1417 /* Cleanup */
1418 if (hManifestVfsFile != NIL_RTVFSFILE)
1419 RTVfsFileRelease(hManifestVfsFile);
1420 if (pvCertBuf)
1421 RTMemFree(pvCertBuf);
1422 if (pShaIo)
1423 RTMemFree(pShaIo);
1424 if (pFileIo)
1425 RTMemFree(pFileIo);
1426
1427 LogFlowFunc(("rc=%Rhrc\n", rc));
1428 LogFlowFuncLeave();
1429
1430 return rc;
1431}
1432
1433HRESULT Appliance::i_importFSOVA(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1434{
1435 LogFlowFuncEnter();
1436 HRESULT rc = S_OK;
1437
1438 /*
1439 * Open the OVA (TAR) file.
1440 */
1441 PFSSRDONLYINTERFACEIO pTarIo;
1442 int vrc = fssRdOnlyCreateInterfaceForTarFile(pTask->locInfo.strPath.c_str(), &pTarIo);
1443 if (RT_FAILURE(vrc))
1444 return setError(VBOX_E_FILE_ERROR,
1445 tr("Could not open OVA file '%s' (%Rrc)"),
1446 pTask->locInfo.strPath.c_str(), vrc);
1447
1448
1449 PVDINTERFACEIO pShaIo = 0;
1450 RTVFSFILE hManifestMemFile = NIL_RTVFSFILE;
1451 void *pvCertBuf = NULL;
1452 Utf8Str OVFfilename;
1453
1454 writeLock.release();
1455
1456 /* Create the import stack for the rollback on errors. */
1457 ImportStack stack(pTask->locInfo, m->pReader->m_mapDisks, pTask->pProgress);
1458 try
1459 {
1460 vrc = RTManifestCreate(0 /*fFlags*/, &stack.hSrcDisksManifest);
1461 if (RT_FAILURE(vrc))
1462 throw setError(E_OUTOFMEMORY);
1463
1464 /* Create the necessary file access interfaces. */
1465 pShaIo = ShaCreateInterface();
1466 if (!pShaIo)
1467 throw setError(E_OUTOFMEMORY);
1468
1469 Utf8Str nameTar = i_applianceIOName(applianceIOTar);
1470 SHASTORAGE storage;
1471 RT_ZERO(storage);
1472 vrc = VDInterfaceAdd((PVDINTERFACE)pTarIo, nameTar.c_str(),
1473 VDINTERFACETYPE_IO, pTarIo, sizeof(VDINTERFACEIO),
1474 &storage.pVDImageIfaces);
1475 if (RT_FAILURE(vrc))
1476 throw setError(VBOX_E_IPRT_ERROR,
1477 tr("Creation of the VD interface failed (%Rrc)"), vrc);
1478
1479 /* Fill out interface descriptor. */
1480 Utf8Str nameSha = i_applianceIOName(applianceIOSha);
1481 pShaIo->Core.u32Magic = VDINTERFACE_MAGIC;
1482 pShaIo->Core.cbSize = sizeof(VDINTERFACEIO);
1483 pShaIo->Core.pszInterfaceName = nameSha.c_str();
1484 pShaIo->Core.enmInterface = VDINTERFACETYPE_IO;
1485 pShaIo->Core.pvUser = &storage;
1486 pShaIo->Core.pNext = NULL;
1487
1488 /*
1489 * File #1 - the .ovf file.
1490 *
1491 * Read the name of the first file. This is how all internal files
1492 * are named.
1493 */
1494 const char *pszFilename;
1495 vrc = fssRdOnlyGetCurrentName(pTarIo, &pszFilename);
1496 if (RT_FAILURE(vrc))
1497 throw setError(VBOX_E_IPRT_ERROR,
1498 tr("Getting the OVF file within the archive failed (%Rrc)"), vrc);
1499 if (vrc == VINF_TAR_DIR_PATH)
1500 throw setError(VBOX_E_FILE_ERROR,
1501 tr("Empty directory folder (%s) isn't allowed in the OVA package (%Rrc)"),
1502 pszFilename, vrc);
1503
1504 /* save original OVF filename */
1505 OVFfilename = pszFilename;
1506 Utf8Str strMfFile = (Utf8Str(pszFilename)).stripSuffix().append(".mf");
1507 Utf8Str strCertFile = (Utf8Str(pszFilename)).stripSuffix().append(".cert");
1508
1509 /* Skip the OVF file, cause this was read in IAppliance::Read already. */
1510 vrc = fssRdOnlySkipCurrent(pTarIo);
1511 if (RT_SUCCESS(vrc))
1512 vrc = fssRdOnlyGetCurrentName(pTarIo, &pszFilename);
1513 if ( RT_FAILURE(vrc)
1514 && vrc != VERR_EOF)
1515 throw setError(VBOX_E_IPRT_ERROR, tr("Seeking within the archive failed (%Rrc)"), vrc);
1516
1517 PVDINTERFACEIO pCallbacks = pShaIo;
1518 PSHASTORAGE pStorage = &storage;
1519
1520 /* We always need to create the digest, cause we don't know if there
1521 * is a manifest file in the stream. */
1522 pStorage->fCreateDigest = true;
1523
1524 /*
1525 * File #2 - the manifest file (.mf), optional.
1526 *
1527 * Note: This isn't fatal if the file is not found. The standard
1528 * defines 3 cases:
1529 * 1. no manifest file
1530 * 2. manifest file after the OVF file
1531 * 3. manifest file after all disk files
1532 *
1533 * If we want streaming capabilities, we can't check if it is there by
1534 * searching for it. We have to try to open it on all possible places.
1535 * If it fails here, we will try it again after all disks where read.
1536 */
1537 /** @todo r=bird: Consider dropping strict ordering and process subsequent files
1538 * as found. This is doable while still sharing code with on disk OVF. It's
1539 * a bit of work though, for OVFs, but more code can ultimately be shared. */
1540 if (fssRdOnlyEqualsCurrentFilename(pTarIo, strMfFile))
1541 {
1542 vrc = fssRdOnlyMemorizeCurrentAsFile(pTarIo, &hManifestMemFile);
1543 if (RT_FAILURE(vrc))
1544 throw setError(VBOX_E_IPRT_ERROR, tr("Failed to read the manifest into a buffer (%Rrc)"), vrc);
1545 }
1546
1547 /*
1548 * File #3 - certificate file (.cer), optional.
1549 *
1550 * Logic is the same as with manifest file. This only makes sense if
1551 * there is a manifest file.
1552 */
1553 size_t cbCertFile = 0;
1554 vrc = fssRdOnlyGetCurrentName(pTarIo, &pszFilename);
1555 if (RT_SUCCESS(vrc))
1556 {
1557 if (hManifestMemFile != NIL_RTVFSFILE)
1558 {
1559 if (strCertFile.compare(pszFilename) == 0)
1560 {
1561 rc = i_readTarFileToBuf(pTarIo, strCertFile, &pvCertBuf, &cbCertFile, false, pCallbacks, pStorage);
1562 if (FAILED(rc)) throw rc;
1563
1564 if (pvCertBuf)
1565 {
1566 /* verify the certificate */
1567 rc = i_verifyCertificateFile(pvCertBuf, cbCertFile, pStorage);
1568 if (FAILED(rc)) throw rc;
1569 }
1570 }
1571 }
1572 }
1573
1574 /*
1575 * Now import the appliance.
1576 */
1577 i_importMachines(stack, pCallbacks, pStorage);
1578
1579 /*
1580 * The certificate and manifest files may alternatively be stored
1581 * after the disk files, so look again if we didn't find them already.
1582 */
1583 if (hManifestMemFile == NIL_RTVFSFILE)
1584 {
1585 /*
1586 * File #N-1 - The manifest file, optional.
1587 */
1588 if (fssRdOnlyEqualsCurrentFilename(pTarIo, strMfFile))
1589 {
1590 vrc = fssRdOnlyMemorizeCurrentAsFile(pTarIo, &hManifestMemFile);
1591 if (RT_FAILURE(vrc))
1592 throw setError(VBOX_E_IPRT_ERROR, tr("Failed to read the manifest into a buffer (%Rrc)"), vrc);
1593
1594 /*
1595 * File #N - The certificate file, optional.
1596 * (Requires mainfest, as mention before.)
1597 */
1598 if (fssRdOnlyEqualsCurrentFilename(pTarIo, strCertFile))
1599 {
1600 rc = i_readTarFileToBuf(pTarIo, strCertFile, &pvCertBuf, &cbCertFile, false, pCallbacks, pStorage);
1601 if (FAILED(rc)) throw rc;
1602 }
1603 }
1604 }
1605
1606 /*
1607 * Check the manifest and its (optional) signature if present.
1608 */
1609 if (hManifestMemFile != NIL_RTVFSFILE)
1610 {
1611 /* Add the ovf file digest to the verification list. */
1612 vrc = RTManifestEntrySetAttr(stack.hSrcDisksManifest, OVFfilename.c_str(), NULL /*pszAttr*/,
1613 m->strOVFSHADigest.c_str(), m->fSha256 ? RTMANIFEST_ATTR_SHA256 : RTMANIFEST_ATTR_SHA1);
1614 if (RT_FAILURE(vrc))
1615 throw setError(VBOX_E_IPRT_ERROR, "RTManifestSetAttr failed on '%s' = '%s' (%Rrc)",
1616 OVFfilename.c_str(), m->strOVFSHADigest.c_str(), vrc);
1617
1618 /* Perform the verifications. */
1619 rc = i_verifyManifestFile(strMfFile, stack, hManifestMemFile, OVFfilename.c_str());
1620 if (FAILED(rc)) throw rc;
1621
1622 /* verify the certificate */
1623 if (pvCertBuf)
1624 {
1625 rc = i_verifyCertificateFile(pvCertBuf, cbCertFile, pStorage);
1626 if (FAILED(rc)) throw rc;
1627 }
1628 }
1629
1630 }
1631 catch (HRESULT rc2)
1632 {
1633 rc = rc2;
1634
1635 /*
1636 * Restoring original UUID from OVF description file.
1637 * During import VBox creates new UUIDs for imported images and
1638 * assigns them to the images. In case of failure we have to restore
1639 * the original UUIDs because those new UUIDs are obsolete now and
1640 * won't be used anymore.
1641 */
1642 ErrorInfoKeeper eik; /* paranoia */
1643 list< ComObjPtr<VirtualSystemDescription> >::const_iterator itvsd;
1644 /* Iterate through all virtual systems of that appliance */
1645 for (itvsd = m->virtualSystemDescriptions.begin();
1646 itvsd != m->virtualSystemDescriptions.end();
1647 ++itvsd)
1648 {
1649 ComObjPtr<VirtualSystemDescription> vsdescThis = (*itvsd);
1650 settings::MachineConfigFile *pConfig = vsdescThis->m->pConfig;
1651 if(vsdescThis->m->pConfig!=NULL)
1652 stack.restoreOriginalUUIDOfAttachedDevice(pConfig);
1653 }
1654 }
1655 writeLock.acquire();
1656
1657 /* Cleanup */
1658 fssRdOnlyDestroyInterface(pTarIo);
1659 if (hManifestMemFile != NIL_RTVFSFILE)
1660 RTVfsFileRelease(hManifestMemFile);
1661 if (pShaIo)
1662 RTMemFree(pShaIo);
1663 if (pvCertBuf)
1664 RTMemFree(pvCertBuf);
1665
1666 LogFlowFunc(("rc=%Rhrc\n", rc));
1667 LogFlowFuncLeave();
1668
1669 return rc;
1670}
1671
1672HRESULT Appliance::i_readFileToBuf(const Utf8Str &strFile,
1673 void **ppvBuf,
1674 size_t *pcbSize,
1675 bool fCreateDigest,
1676 PVDINTERFACEIO pCallbacks,
1677 PSHASTORAGE pStorage)
1678{
1679 HRESULT rc = S_OK;
1680
1681 bool fOldDigest = pStorage->fCreateDigest;/* Save the old digest property */
1682 pStorage->fCreateDigest = fCreateDigest;
1683 int vrc = readFileIntoBuffer(strFile.c_str(), ppvBuf, pcbSize, pCallbacks, pStorage);
1684 if ( RT_FAILURE(vrc)
1685 && vrc != VERR_FILE_NOT_FOUND)
1686 rc = setError(VBOX_E_FILE_ERROR,
1687 tr("Could not read file '%s' (%Rrc)"),
1688 RTPathFilename(strFile.c_str()), vrc);
1689 pStorage->fCreateDigest = fOldDigest; /* Restore the old digest creation behavior again. */
1690
1691 return rc;
1692}
1693
1694HRESULT Appliance::i_readTarFileToBuf(PFSSRDONLYINTERFACEIO pTarIo,
1695 const Utf8Str &strFile,
1696 void **ppvBuf,
1697 size_t *pcbSize,
1698 bool fCreateDigest,
1699 PVDINTERFACEIO pCallbacks,
1700 PSHASTORAGE pStorage)
1701{
1702 HRESULT rc = S_OK;
1703
1704 const char *pszCurFile;
1705 int vrc = fssRdOnlyGetCurrentName(pTarIo, &pszCurFile);
1706 if (RT_SUCCESS(vrc))
1707 {
1708 if (vrc != VINF_TAR_DIR_PATH)
1709 {
1710 if (!strcmp(pszCurFile, RTPathFilename(strFile.c_str())))
1711 rc = i_readFileToBuf(strFile, ppvBuf, pcbSize, fCreateDigest, pCallbacks, pStorage);
1712 }
1713 else
1714 rc = setError(VBOX_E_FILE_ERROR,
1715 tr("Empty directory folder (%s) isn't allowed in the OVA package (%Rrc)"),
1716 pszCurFile, vrc);
1717 }
1718 else if (vrc != VERR_EOF)
1719 rc = setError(VBOX_E_IPRT_ERROR, "Seeking within the archive failed (%Rrc)", vrc);
1720
1721 return rc;
1722}
1723
1724/**
1725 * Undocumented, you figure it from the name.
1726 *
1727 * @returns Undocumented
1728 * @param strFile Undocumented.
1729 * @param stack Undocumented.
1730 * @param hManifestVfsFile A VFS file object containing the manifest. This
1731 * can be a buffered memory file or a read file.
1732 * @param pszOvfEntry The name of the manifest entry for the OVF (for
1733 * the ignore hack).
1734 */
1735HRESULT Appliance::i_verifyManifestFile(const Utf8Str &strFile, ImportStack &stack,
1736 RTVFSFILE hManifestVfsFile, const char *pszOvfEntry)
1737{
1738 LogFlowThisFuncEnter();
1739 HRESULT hrc;
1740
1741 /*
1742 * Parse the manifest file associated with the import.
1743 */
1744 RTMANIFEST hOvfManifest;
1745 int vrc = RTManifestCreate(0 /*fFlags*/, &hOvfManifest);
1746 if (RT_SUCCESS(vrc))
1747 {
1748 char szErr[256];
1749 RTVFSIOSTREAM hVfsIosTmp = RTVfsFileToIoStream(hManifestVfsFile);
1750 vrc = RTManifestReadStandardEx(hOvfManifest, hVfsIosTmp, szErr, sizeof(szErr));
1751 RTVfsIoStrmRelease(hVfsIosTmp);
1752 if (RT_SUCCESS(vrc))
1753 {
1754 /** @todo Do we need to chop paths off the files in any of the manifests before
1755 * comparing? */
1756
1757 /*
1758 * Hack: If the manifest we just read doesn't have a digest for the OVF, copy
1759 * it from the manifest we got from the caller.
1760 * @bugref{6022#c119}
1761 */
1762 if ( !RTManifestEntryExists(hOvfManifest, pszOvfEntry)
1763 && RTManifestEntryExists(stack.hSrcDisksManifest, pszOvfEntry) )
1764 {
1765 uint32_t fType = 0;
1766 char szDigest[512 + 1];
1767 vrc = RTManifestEntryQueryAttr(stack.hSrcDisksManifest, pszOvfEntry, NULL, RTMANIFEST_ATTR_ANY,
1768 szDigest, sizeof(szDigest), &fType);
1769 if (RT_SUCCESS(vrc))
1770 vrc = RTManifestEntrySetAttr(hOvfManifest, pszOvfEntry, NULL /*pszAttr*/, szDigest, fType);
1771 }
1772 if (RT_SUCCESS(vrc))
1773 {
1774 /*
1775 * Compare with the digests we've created while read/processing the import.
1776 */
1777 vrc = RTManifestEqualsEx(hOvfManifest, stack.hSrcDisksManifest, NULL /*papszIgnoreEntries*/,
1778 NULL /*papszIgnoreAttrs*/, 0 /*fFlags*/, szErr, sizeof(szErr));
1779 if (RT_SUCCESS(vrc))
1780 hrc = S_OK;
1781 else
1782 hrc = setError(VBOX_E_IPRT_ERROR, tr("Digest mismatch (%Rrc): %s"), vrc, szErr);
1783 }
1784 else
1785 hrc = setError(VBOX_E_IPRT_ERROR, tr("Error fudging missing OVF digest in manifest: %Rrc"), vrc);
1786 }
1787 else
1788 hrc = setError(VBOX_E_IPRT_ERROR, tr("Error reading manifest (%s): %Rrc - %s"), strFile.c_str(), vrc, szErr);
1789
1790 RTManifestRelease(hOvfManifest);
1791 }
1792 else
1793 hrc = Global::vboxStatusCodeToCOM(vrc);
1794
1795 LogFlowThisFuncLeave();
1796 return hrc;
1797}
1798
1799HRESULT Appliance::i_verifyCertificateFile(void *pvBuf, size_t cbSize, PSHASTORAGE pStorage)
1800{
1801 LogFlowFuncEnter();
1802 LogFlowFunc(("Appliance %p\n", this));
1803 HRESULT rc = S_OK;
1804
1805 int vrc = 0;
1806 RTDIGESTTYPE digestType;
1807 void * pvCertBuf = pvBuf;
1808 size_t cbCertSize = cbSize;
1809 Utf8Str manifestDigest = pStorage->strDigest;
1810
1811 vrc = RTManifestVerifyDigestType(pvCertBuf, cbCertSize, &digestType);
1812 if (RT_FAILURE(vrc))
1813 {
1814 rc = setError(VBOX_E_FILE_ERROR, tr("Digest type of certificate is unknown"));
1815 }
1816 else
1817 {
1818 RTX509PrepareOpenSSL();
1819
1820 vrc = RTRSAVerify(pvCertBuf, (unsigned int)cbCertSize, manifestDigest.c_str(), digestType);
1821 if (RT_SUCCESS(vrc))
1822 {
1823 /*
1824 * possible step in the future. Not obligatory due to OVF2.0 standard
1825 * OVF2.0:"A consumer of the OVF package shall verify the signature and should validate the certificate"
1826 */
1827 vrc = RTX509CertificateVerify(pvCertBuf, (unsigned int)cbCertSize);
1828 }
1829
1830 /* After first unsuccessful operation */
1831 if (RT_FAILURE(vrc))
1832 {
1833 {
1834 /* first stage for getting possible error code and it's description using native openssl method */
1835 char* errStrDesc = NULL;
1836 unsigned long errValue = RTX509GetErrorDescription(&errStrDesc);
1837
1838 if(errValue != 0)
1839 {
1840 rc = setError(VBOX_E_FILE_ERROR, tr(errStrDesc));
1841 LogFlowFunc(("Error during verifying X509 certificate(internal openssl description): %s\n", errStrDesc));
1842 }
1843
1844 RTMemFree(errStrDesc);
1845 }
1846
1847 {
1848 /* second stage for getting possible error code using our defined errors codes. The original error description
1849 will be replaced by our description */
1850
1851 Utf8Str errStrDesc;
1852 switch(vrc)
1853 {
1854 case VERR_X509_READING_CERT_FROM_BIO:
1855 errStrDesc = "Error during reading a certificate in PEM format from BIO ";
1856 break;
1857 case VERR_X509_EXTRACT_PUBKEY_FROM_CERT:
1858 errStrDesc = "Error during extraction a public key from the certificate ";
1859 break;
1860 case VERR_X509_EXTRACT_RSA_FROM_PUBLIC_KEY:
1861 errStrDesc = "Error during extraction RSA from the public key ";
1862 break;
1863 case VERR_X509_RSA_VERIFICATION_FUILURE:
1864 errStrDesc = "RSA verification failure ";
1865 break;
1866 case VERR_X509_NO_BASIC_CONSTARAINTS:
1867 errStrDesc = "Basic constraints were not found ";
1868 break;
1869 case VERR_X509_GETTING_EXTENSION_FROM_CERT:
1870 errStrDesc = "Error during getting extensions from the certificate ";
1871 break;
1872 case VERR_X509_GETTING_DATA_FROM_EXTENSION:
1873 errStrDesc = "Error during extraction data from the extension ";
1874 break;
1875 case VERR_X509_PRINT_EXTENSION_TO_BIO:
1876 errStrDesc = "Error during print out an extension to BIO ";
1877 break;
1878 case VERR_X509_CERTIFICATE_VERIFICATION_FAILURE:
1879 errStrDesc = "X509 certificate verification failure ";
1880 break;
1881 default:
1882 errStrDesc = "Unknown error during X509 certificate verification";
1883 }
1884 rc = setError(VBOX_E_FILE_ERROR, tr(errStrDesc.c_str()));
1885 }
1886 }
1887 else
1888 {
1889 if(vrc == VINF_X509_NOT_SELFSIGNED_CERTIFICATE)
1890 {
1891 setWarning(VBOX_E_FILE_ERROR,
1892 tr("Signature from the X509 certificate has been verified. "
1893 "But VirtualBox can't validate the given X509 certificate. "
1894 "Only self signed X509 certificates are supported at moment. \n"));
1895 }
1896 }
1897 }
1898
1899 LogFlowFuncLeave();
1900 return rc;
1901}
1902
1903/**
1904 * Helper that converts VirtualSystem attachment values into VirtualBox attachment values.
1905 * Throws HRESULT values on errors!
1906 *
1907 * @param hdc in: the HardDiskController structure to attach to.
1908 * @param ulAddressOnParent in: the AddressOnParent parameter from OVF.
1909 * @param controllerType out: the name of the hard disk controller to attach to (e.g. "IDE Controller").
1910 * @param lControllerPort out: the channel (controller port) of the controller to attach to.
1911 * @param lDevice out: the device number to attach to.
1912 */
1913void Appliance::i_convertDiskAttachmentValues(const ovf::HardDiskController &hdc,
1914 uint32_t ulAddressOnParent,
1915 Bstr &controllerType,
1916 int32_t &lControllerPort,
1917 int32_t &lDevice)
1918{
1919 Log(("Appliance::i_convertDiskAttachmentValues: hdc.system=%d, hdc.fPrimary=%d, ulAddressOnParent=%d\n",
1920 hdc.system,
1921 hdc.fPrimary,
1922 ulAddressOnParent));
1923
1924 switch (hdc.system)
1925 {
1926 case ovf::HardDiskController::IDE:
1927 // For the IDE bus, the port parameter can be either 0 or 1, to specify the primary
1928 // or secondary IDE controller, respectively. For the primary controller of the IDE bus,
1929 // the device number can be either 0 or 1, to specify the master or the slave device,
1930 // respectively. For the secondary IDE controller, the device number is always 1 because
1931 // the master device is reserved for the CD-ROM drive.
1932 controllerType = Bstr("IDE Controller");
1933 switch (ulAddressOnParent)
1934 {
1935 case 0: // master
1936 if (!hdc.fPrimary)
1937 {
1938 // secondary master
1939 lControllerPort = (long)1;
1940 lDevice = (long)0;
1941 }
1942 else // primary master
1943 {
1944 lControllerPort = (long)0;
1945 lDevice = (long)0;
1946 }
1947 break;
1948
1949 case 1: // slave
1950 if (!hdc.fPrimary)
1951 {
1952 // secondary slave
1953 lControllerPort = (long)1;
1954 lDevice = (long)1;
1955 }
1956 else // primary slave
1957 {
1958 lControllerPort = (long)0;
1959 lDevice = (long)1;
1960 }
1961 break;
1962
1963 // used by older VBox exports
1964 case 2: // interpret this as secondary master
1965 lControllerPort = (long)1;
1966 lDevice = (long)0;
1967 break;
1968
1969 // used by older VBox exports
1970 case 3: // interpret this as secondary slave
1971 lControllerPort = (long)1;
1972 lDevice = (long)1;
1973 break;
1974
1975 default:
1976 throw setError(VBOX_E_NOT_SUPPORTED,
1977 tr("Invalid channel %RI16 specified; IDE controllers support only 0, 1 or 2"),
1978 ulAddressOnParent);
1979 break;
1980 }
1981 break;
1982
1983 case ovf::HardDiskController::SATA:
1984 controllerType = Bstr("SATA Controller");
1985 lControllerPort = (long)ulAddressOnParent;
1986 lDevice = (long)0;
1987 break;
1988
1989 case ovf::HardDiskController::SCSI:
1990 {
1991 if(hdc.strControllerType.compare("lsilogicsas")==0)
1992 controllerType = Bstr("SAS Controller");
1993 else
1994 controllerType = Bstr("SCSI Controller");
1995 lControllerPort = (long)ulAddressOnParent;
1996 lDevice = (long)0;
1997 }
1998 break;
1999
2000 default: break;
2001 }
2002
2003 Log(("=> lControllerPort=%d, lDevice=%d\n", lControllerPort, lDevice));
2004}
2005
2006/**
2007 * Imports one disk image. This is common code shared between
2008 * -- i_importMachineGeneric() for the OVF case; in that case the information comes from
2009 * the OVF virtual systems;
2010 * -- i_importVBoxMachine(); in that case, the information comes from the <vbox:Machine>
2011 * tag.
2012 *
2013 * Both ways of describing machines use the OVF disk references section, so in both cases
2014 * the caller needs to pass in the ovf::DiskImage structure from ovfreader.cpp.
2015 *
2016 * As a result, in both cases, if di.strHref is empty, we create a new disk as per the OVF
2017 * spec, even though this cannot really happen in the vbox:Machine case since such data
2018 * would never have been exported.
2019 *
2020 * This advances stack.pProgress by one operation with the disk's weight.
2021 *
2022 * @param di ovfreader.cpp structure describing the disk image from the OVF that is to be imported
2023 * @param strTargetPath Where to create the target image.
2024 * @param pTargetHD out: The newly created target disk. This also gets pushed on stack.llHardDisksCreated for cleanup.
2025 * @param stack
2026 */
2027void Appliance::i_importOneDiskImage(const ovf::DiskImage &di,
2028 Utf8Str *strTargetPath,
2029 ComObjPtr<Medium> &pTargetHD,
2030 ImportStack &stack,
2031 PVDINTERFACEIO pCallbacks,
2032 PSHASTORAGE pStorage)
2033{
2034 SHASTORAGE finalStorage;
2035 PSHASTORAGE pRealUsedStorage = pStorage;/* may be changed later to finalStorage */
2036 PVDINTERFACEIO pFileIo = NULL;/* used in GZIP case*/
2037 ComObjPtr<Progress> pProgress;
2038 pProgress.createObject();
2039 HRESULT rc = pProgress->init(mVirtualBox,
2040 static_cast<IAppliance*>(this),
2041 BstrFmt(tr("Creating medium '%s'"),
2042 strTargetPath->c_str()).raw(),
2043 TRUE);
2044 if (FAILED(rc)) throw rc;
2045
2046 /* Get the system properties. */
2047 SystemProperties *pSysProps = mVirtualBox->i_getSystemProperties();
2048
2049 /* Keep the source file ref handy for later. */
2050 const Utf8Str &strSourceOVF = di.strHref;
2051
2052 Utf8Str strSrcFilePath(stack.strSourceDir);
2053 Utf8Str strTargetDir(*strTargetPath);
2054
2055 /* Construct source file path */
2056 Utf8Str name = i_applianceIOName(applianceIOTar);
2057
2058 if (RTStrNICmp(pStorage->pVDImageIfaces->pszInterfaceName, name.c_str(), name.length()) == 0)
2059 strSrcFilePath = strSourceOVF;
2060 else
2061 {
2062 strSrcFilePath.append(RTPATH_SLASH_STR);
2063 strSrcFilePath.append(strSourceOVF);
2064 }
2065
2066 /* First of all check if the path is an UUID. If so, the user like to
2067 * import the disk into an existing path. This is useful for iSCSI for
2068 * example. */
2069 RTUUID uuid;
2070 int vrc = RTUuidFromStr(&uuid, strTargetPath->c_str());
2071 if (vrc == VINF_SUCCESS)
2072 {
2073 rc = mVirtualBox->i_findHardDiskById(Guid(uuid), true, &pTargetHD);
2074 if (FAILED(rc)) throw rc;
2075 }
2076 else
2077 {
2078 bool fGzipUsed = di.strCompression.compare("gzip",Utf8Str::CaseInsensitive) == 0;
2079 /* check read file to GZIP compression */
2080 try
2081 {
2082 if (fGzipUsed == true)
2083 {
2084 /*
2085 * Create the necessary file access interfaces.
2086 * For the next step:
2087 * We need to replace the previously created chain of SHA-TAR or SHA-FILE interfaces
2088 * with simple FILE interface because we don't need SHA or TAR interfaces here anymore.
2089 * But we mustn't delete the chain of SHA-TAR or SHA-FILE interfaces.
2090 */
2091
2092 /* Decompress the GZIP file and save a new file in the target path */
2093 strTargetDir = strTargetDir.stripFilename();
2094 strTargetDir.append(RTPATH_SLASH_STR);
2095 strTargetDir.append("temp_");
2096
2097 Utf8Str strTempTargetFilename(strSrcFilePath);
2098 strTempTargetFilename = strTempTargetFilename.stripPath();
2099
2100 strTargetDir.append(strTempTargetFilename);
2101
2102 vrc = decompressImageAndSave(strSrcFilePath.c_str(), strTargetDir.c_str(), pCallbacks, pStorage);
2103
2104 if (RT_FAILURE(vrc))
2105 throw setError(VBOX_E_FILE_ERROR,
2106 tr("Could not read the file '%s' (%Rrc)"),
2107 RTPathFilename(strSrcFilePath.c_str()), vrc);
2108
2109 /* Create the necessary file access interfaces. */
2110 pFileIo = FileCreateInterface();
2111 if (!pFileIo)
2112 throw setError(E_OUTOFMEMORY);
2113
2114 name = i_applianceIOName(applianceIOFile);
2115
2116 vrc = VDInterfaceAdd(&pFileIo->Core, name.c_str(),
2117 VDINTERFACETYPE_IO, NULL, sizeof(VDINTERFACEIO),
2118 &finalStorage.pVDImageIfaces);
2119 if (RT_FAILURE(vrc))
2120 throw setError(VBOX_E_IPRT_ERROR,
2121 tr("Creation of the VD interface failed (%Rrc)"), vrc);
2122
2123 /* Correct the source and the target with the actual values */
2124 strSrcFilePath = strTargetDir;
2125
2126 pRealUsedStorage = &finalStorage;
2127 }
2128
2129 Utf8Str strTrgFormat = "VMDK";
2130 ComObjPtr<MediumFormat> trgFormat;
2131 Bstr bstrFormatName;
2132 ULONG lCabs = 0;
2133
2134 //check existence of option "ImportToVDI", in this case all imported disks will be converted to VDI images
2135 bool chExt = m->optListImport.contains(ImportOptions_ImportToVDI);
2136
2137 char *pszSuff = RTPathSuffix(strTargetPath->c_str());
2138 if (pszSuff != NULL)
2139 {
2140 /*
2141 * Figure out which format the user like to have. Default is VMDK
2142 * or it can be VDI if according command-line option is set
2143 */
2144
2145 /*
2146 * We need a proper target format
2147 * if target format has been changed by user via GUI import wizard
2148 * or via VBoxManage import command (option --importtovdi)
2149 * then we need properly process such format like ISO
2150 * Because there is no conversion ISO to VDI
2151 */
2152
2153 pszSuff++;
2154 trgFormat = pSysProps->i_mediumFormatFromExtension(pszSuff);
2155 if (trgFormat.isNull())
2156 {
2157 rc = setError(E_FAIL,
2158 tr("Internal inconsistency looking up medium format for the disk image '%s'"),
2159 di.strHref.c_str());
2160 }
2161
2162 rc = trgFormat->COMGETTER(Name)(bstrFormatName.asOutParam());
2163 if (FAILED(rc)) throw rc;
2164
2165 strTrgFormat = Utf8Str(bstrFormatName);
2166
2167 if(chExt && strTrgFormat.compare("RAW", Utf8Str::CaseInsensitive) != 0)
2168 {
2169 /* change the target extension */
2170 strTrgFormat = "vdi";
2171 trgFormat = pSysProps->i_mediumFormatFromExtension(strTrgFormat);
2172 *strTargetPath = strTargetPath->stripSuffix();
2173 *strTargetPath = strTargetPath->append(".");
2174 *strTargetPath = strTargetPath->append(strTrgFormat.c_str());
2175 }
2176
2177 /* Check the capabilities. We need create capabilities. */
2178 lCabs = 0;
2179 com::SafeArray <MediumFormatCapabilities_T> mediumFormatCap;
2180 rc = trgFormat->COMGETTER(Capabilities)(ComSafeArrayAsOutParam(mediumFormatCap));
2181
2182 if (FAILED(rc))
2183 throw rc;
2184
2185 for (ULONG j = 0; j < mediumFormatCap.size(); j++)
2186 lCabs |= mediumFormatCap[j];
2187
2188 if ( !(lCabs & MediumFormatCapabilities_CreateFixed)
2189 && !(lCabs & MediumFormatCapabilities_CreateDynamic) )
2190 throw setError(VBOX_E_NOT_SUPPORTED,
2191 tr("Could not find a valid medium format for the target disk '%s'"),
2192 strTargetPath->c_str());
2193 }
2194 else
2195 {
2196 throw setError(VBOX_E_FILE_ERROR,
2197 tr("The target disk '%s' has no extension "),
2198 strTargetPath->c_str(), VERR_INVALID_NAME);
2199 }
2200
2201 /* Create an IMedium object. */
2202 pTargetHD.createObject();
2203
2204 /*CD/DVD case*/
2205 if (strTrgFormat.compare("RAW", Utf8Str::CaseInsensitive) == 0)
2206 {
2207 try
2208 {
2209 if (fGzipUsed == true)
2210 {
2211 /*
2212 * The source and target pathes are the same.
2213 * It means that we have the needed file already.
2214 * For example, in GZIP case, we decompress the file and save it in the target path,
2215 * but with some prefix like "temp_". See part "check read file to GZIP compression" earlier
2216 * in this function.
2217 * Just rename the file by deleting "temp_" from it's name
2218 */
2219 vrc = RTFileRename(strSrcFilePath.c_str(), strTargetPath->c_str(), RTPATHRENAME_FLAGS_NO_REPLACE);
2220 if (RT_FAILURE(vrc))
2221 throw setError(VBOX_E_FILE_ERROR,
2222 tr("Could not rename the file '%s' (%Rrc)"),
2223 RTPathFilename(strSourceOVF.c_str()), vrc);
2224 }
2225 else
2226 {
2227 /* Calculating SHA digest for ISO file while copying one */
2228 vrc = copyFileAndCalcShaDigest(strSrcFilePath.c_str(),
2229 strTargetPath->c_str(),
2230 pCallbacks,
2231 pRealUsedStorage);
2232
2233 if (RT_FAILURE(vrc))
2234 throw setError(VBOX_E_FILE_ERROR,
2235 tr("Could not copy ISO file '%s' listed in the OVF file (%Rrc)"),
2236 RTPathFilename(strSourceOVF.c_str()), vrc);
2237 }
2238 }
2239 catch (HRESULT /*arc*/)
2240 {
2241 throw;
2242 }
2243
2244 /* Advance to the next operation. */
2245 /* operation's weight, as set up with the IProgress originally */
2246 stack.pProgress->SetNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"),
2247 RTPathFilename(strSourceOVF.c_str())).raw(),
2248 di.ulSuggestedSizeMB);
2249 }
2250 else/* HDD case*/
2251 {
2252 rc = pTargetHD->init(mVirtualBox,
2253 strTrgFormat,
2254 *strTargetPath,
2255 Guid::Empty /* media registry: none yet */,
2256 DeviceType_HardDisk);
2257 if (FAILED(rc)) throw rc;
2258
2259 /* Now create an empty hard disk. */
2260 rc = mVirtualBox->CreateMedium(Bstr(strTrgFormat).raw(),
2261 Bstr(*strTargetPath).raw(),
2262 AccessMode_ReadWrite, DeviceType_HardDisk,
2263 ComPtr<IMedium>(pTargetHD).asOutParam());
2264 if (FAILED(rc)) throw rc;
2265
2266 /* If strHref is empty we have to create a new file. */
2267 if (strSourceOVF.isEmpty())
2268 {
2269 com::SafeArray<MediumVariant_T> mediumVariant;
2270 mediumVariant.push_back(MediumVariant_Standard);
2271 /* Create a dynamic growing disk image with the given capacity. */
2272 rc = pTargetHD->CreateBaseStorage(di.iCapacity / _1M,
2273 ComSafeArrayAsInParam(mediumVariant),
2274 ComPtr<IProgress>(pProgress).asOutParam());
2275 if (FAILED(rc)) throw rc;
2276
2277 /* Advance to the next operation. */
2278 /* operation's weight, as set up with the IProgress originally */
2279 stack.pProgress->SetNextOperation(BstrFmt(tr("Creating disk image '%s'"),
2280 strTargetPath->c_str()).raw(),
2281 di.ulSuggestedSizeMB);
2282 }
2283 else
2284 {
2285 /* We need a proper source format description */
2286 /* Which format to use? */
2287 ComObjPtr<MediumFormat> srcFormat;
2288 rc = i_findMediumFormatFromDiskImage(di, srcFormat);
2289 if (FAILED(rc))
2290 throw setError(VBOX_E_NOT_SUPPORTED,
2291 tr("Could not find a valid medium format for the source disk '%s' "
2292 "Check correctness of the image format URL in the OVF description file "
2293 "or extension of the image"),
2294 RTPathFilename(strSourceOVF.c_str()));
2295
2296 /* Clone the source disk image */
2297 ComObjPtr<Medium> nullParent;
2298 rc = pTargetHD->i_importFile(strSrcFilePath.c_str(),
2299 srcFormat,
2300 MediumVariant_Standard,
2301 pCallbacks, pRealUsedStorage,
2302 nullParent,
2303 pProgress);
2304 if (FAILED(rc)) throw rc;
2305
2306
2307
2308 /* Advance to the next operation. */
2309 /* operation's weight, as set up with the IProgress originally */
2310 stack.pProgress->SetNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"),
2311 RTPathFilename(strSourceOVF.c_str())).raw(),
2312 di.ulSuggestedSizeMB);
2313 }
2314
2315 /* Now wait for the background disk operation to complete; this throws
2316 * HRESULTs on error. */
2317 ComPtr<IProgress> pp(pProgress);
2318 i_waitForAsyncProgress(stack.pProgress, pp);
2319
2320 if (fGzipUsed == true)
2321 {
2322 /*
2323 * Just delete the temporary file
2324 */
2325 vrc = RTFileDelete(strSrcFilePath.c_str());
2326 if (RT_FAILURE(vrc))
2327 setWarning(VBOX_E_FILE_ERROR,
2328 tr("Could not delete the file '%s' (%Rrc)"),
2329 RTPathFilename(strSrcFilePath.c_str()), vrc);
2330 }
2331 }
2332 }
2333 catch (...)
2334 {
2335 if (pFileIo)
2336 RTMemFree(pFileIo);
2337
2338 throw;
2339 }
2340 }
2341
2342 if (pFileIo)
2343 RTMemFree(pFileIo);
2344
2345 /* Add the newly create disk path + a corresponding digest the our list for
2346 * later manifest verification. */
2347 if (pStorage) /** @todo figure out when this undocumented parameter could be NULL and what implications it has. */
2348 {
2349 vrc = RTManifestEntrySetAttr(stack.hSrcDisksManifest,
2350 strSourceOVF.c_str(),
2351 NULL /*pszAttr*/,
2352 pStorage->strDigest.c_str(),
2353 pStorage->fSha256 ? RTMANIFEST_ATTR_SHA256 : RTMANIFEST_ATTR_SHA1);
2354 if (RT_FAILURE(vrc))
2355 throw setError(VBOX_E_IPRT_ERROR, "RTManifestSetAttr failed on '%s' = '%s' (%Rrc)",
2356 strSourceOVF.c_str(), pStorage->strDigest.c_str(), vrc);
2357 }
2358}
2359
2360/**
2361 * Imports one OVF virtual system (described by the given ovf::VirtualSystem and VirtualSystemDescription)
2362 * into VirtualBox by creating an IMachine instance, which is returned.
2363 *
2364 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
2365 * up any leftovers from this function. For this, the given ImportStack instance has received information
2366 * about what needs cleaning up (to support rollback).
2367 *
2368 * @param vsysThis OVF virtual system (machine) to import.
2369 * @param vsdescThis Matching virtual system description (machine) to import.
2370 * @param pNewMachine out: Newly created machine.
2371 * @param stack Cleanup stack for when this throws.
2372 */
2373void Appliance::i_importMachineGeneric(const ovf::VirtualSystem &vsysThis,
2374 ComObjPtr<VirtualSystemDescription> &vsdescThis,
2375 ComPtr<IMachine> &pNewMachine,
2376 ImportStack &stack,
2377 PVDINTERFACEIO pCallbacks,
2378 PSHASTORAGE pStorage)
2379{
2380 LogFlowFuncEnter();
2381 HRESULT rc;
2382
2383 // Get the instance of IGuestOSType which matches our string guest OS type so we
2384 // can use recommended defaults for the new machine where OVF doesn't provide any
2385 ComPtr<IGuestOSType> osType;
2386 rc = mVirtualBox->GetGuestOSType(Bstr(stack.strOsTypeVBox).raw(), osType.asOutParam());
2387 if (FAILED(rc)) throw rc;
2388
2389 /* Create the machine */
2390 SafeArray<BSTR> groups; /* no groups */
2391 rc = mVirtualBox->CreateMachine(NULL, /* machine name: use default */
2392 Bstr(stack.strNameVBox).raw(),
2393 ComSafeArrayAsInParam(groups),
2394 Bstr(stack.strOsTypeVBox).raw(),
2395 NULL, /* aCreateFlags */
2396 pNewMachine.asOutParam());
2397 if (FAILED(rc)) throw rc;
2398
2399 // set the description
2400 if (!stack.strDescription.isEmpty())
2401 {
2402 rc = pNewMachine->COMSETTER(Description)(Bstr(stack.strDescription).raw());
2403 if (FAILED(rc)) throw rc;
2404 }
2405
2406 // CPU count
2407 rc = pNewMachine->COMSETTER(CPUCount)(stack.cCPUs);
2408 if (FAILED(rc)) throw rc;
2409
2410 if (stack.fForceHWVirt)
2411 {
2412 rc = pNewMachine->SetHWVirtExProperty(HWVirtExPropertyType_Enabled, TRUE);
2413 if (FAILED(rc)) throw rc;
2414 }
2415
2416 // RAM
2417 rc = pNewMachine->COMSETTER(MemorySize)(stack.ulMemorySizeMB);
2418 if (FAILED(rc)) throw rc;
2419
2420 /* VRAM */
2421 /* Get the recommended VRAM for this guest OS type */
2422 ULONG vramVBox;
2423 rc = osType->COMGETTER(RecommendedVRAM)(&vramVBox);
2424 if (FAILED(rc)) throw rc;
2425
2426 /* Set the VRAM */
2427 rc = pNewMachine->COMSETTER(VRAMSize)(vramVBox);
2428 if (FAILED(rc)) throw rc;
2429
2430 // I/O APIC: Generic OVF has no setting for this. Enable it if we
2431 // import a Windows VM because if if Windows was installed without IOAPIC,
2432 // it will not mind finding an one later on, but if Windows was installed
2433 // _with_ an IOAPIC, it will bluescreen if it's not found
2434 if (!stack.fForceIOAPIC)
2435 {
2436 Bstr bstrFamilyId;
2437 rc = osType->COMGETTER(FamilyId)(bstrFamilyId.asOutParam());
2438 if (FAILED(rc)) throw rc;
2439 if (bstrFamilyId == "Windows")
2440 stack.fForceIOAPIC = true;
2441 }
2442
2443 if (stack.fForceIOAPIC)
2444 {
2445 ComPtr<IBIOSSettings> pBIOSSettings;
2446 rc = pNewMachine->COMGETTER(BIOSSettings)(pBIOSSettings.asOutParam());
2447 if (FAILED(rc)) throw rc;
2448
2449 rc = pBIOSSettings->COMSETTER(IOAPICEnabled)(TRUE);
2450 if (FAILED(rc)) throw rc;
2451 }
2452
2453 if (!stack.strAudioAdapter.isEmpty())
2454 if (stack.strAudioAdapter.compare("null", Utf8Str::CaseInsensitive) != 0)
2455 {
2456 uint32_t audio = RTStrToUInt32(stack.strAudioAdapter.c_str()); // should be 0 for AC97
2457 ComPtr<IAudioAdapter> audioAdapter;
2458 rc = pNewMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam());
2459 if (FAILED(rc)) throw rc;
2460 rc = audioAdapter->COMSETTER(Enabled)(true);
2461 if (FAILED(rc)) throw rc;
2462 rc = audioAdapter->COMSETTER(AudioController)(static_cast<AudioControllerType_T>(audio));
2463 if (FAILED(rc)) throw rc;
2464 }
2465
2466#ifdef VBOX_WITH_USB
2467 /* USB Controller */
2468 if (stack.fUSBEnabled)
2469 {
2470 ComPtr<IUSBController> usbController;
2471 rc = pNewMachine->AddUSBController(Bstr("OHCI").raw(), USBControllerType_OHCI, usbController.asOutParam());
2472 if (FAILED(rc)) throw rc;
2473 }
2474#endif /* VBOX_WITH_USB */
2475
2476 /* Change the network adapters */
2477 uint32_t maxNetworkAdapters = Global::getMaxNetworkAdapters(ChipsetType_PIIX3);
2478
2479 std::list<VirtualSystemDescriptionEntry*> vsdeNW = vsdescThis->i_findByType(VirtualSystemDescriptionType_NetworkAdapter);
2480 if (vsdeNW.empty())
2481 {
2482 /* No network adapters, so we have to disable our default one */
2483 ComPtr<INetworkAdapter> nwVBox;
2484 rc = pNewMachine->GetNetworkAdapter(0, nwVBox.asOutParam());
2485 if (FAILED(rc)) throw rc;
2486 rc = nwVBox->COMSETTER(Enabled)(false);
2487 if (FAILED(rc)) throw rc;
2488 }
2489 else if (vsdeNW.size() > maxNetworkAdapters)
2490 throw setError(VBOX_E_FILE_ERROR,
2491 tr("Too many network adapters: OVF requests %d network adapters, "
2492 "but VirtualBox only supports %d"),
2493 vsdeNW.size(), maxNetworkAdapters);
2494 else
2495 {
2496 list<VirtualSystemDescriptionEntry*>::const_iterator nwIt;
2497 size_t a = 0;
2498 for (nwIt = vsdeNW.begin();
2499 nwIt != vsdeNW.end();
2500 ++nwIt, ++a)
2501 {
2502 const VirtualSystemDescriptionEntry* pvsys = *nwIt;
2503
2504 const Utf8Str &nwTypeVBox = pvsys->strVBoxCurrent;
2505 uint32_t tt1 = RTStrToUInt32(nwTypeVBox.c_str());
2506 ComPtr<INetworkAdapter> pNetworkAdapter;
2507 rc = pNewMachine->GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
2508 if (FAILED(rc)) throw rc;
2509 /* Enable the network card & set the adapter type */
2510 rc = pNetworkAdapter->COMSETTER(Enabled)(true);
2511 if (FAILED(rc)) throw rc;
2512 rc = pNetworkAdapter->COMSETTER(AdapterType)(static_cast<NetworkAdapterType_T>(tt1));
2513 if (FAILED(rc)) throw rc;
2514
2515 // default is NAT; change to "bridged" if extra conf says so
2516 if (pvsys->strExtraConfigCurrent.endsWith("type=Bridged", Utf8Str::CaseInsensitive))
2517 {
2518 /* Attach to the right interface */
2519 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_Bridged);
2520 if (FAILED(rc)) throw rc;
2521 ComPtr<IHost> host;
2522 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
2523 if (FAILED(rc)) throw rc;
2524 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
2525 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
2526 if (FAILED(rc)) throw rc;
2527 // We search for the first host network interface which
2528 // is usable for bridged networking
2529 for (size_t j = 0;
2530 j < nwInterfaces.size();
2531 ++j)
2532 {
2533 HostNetworkInterfaceType_T itype;
2534 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
2535 if (FAILED(rc)) throw rc;
2536 if (itype == HostNetworkInterfaceType_Bridged)
2537 {
2538 Bstr name;
2539 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
2540 if (FAILED(rc)) throw rc;
2541 /* Set the interface name to attach to */
2542 rc = pNetworkAdapter->COMSETTER(BridgedInterface)(name.raw());
2543 if (FAILED(rc)) throw rc;
2544 break;
2545 }
2546 }
2547 }
2548 /* Next test for host only interfaces */
2549 else if (pvsys->strExtraConfigCurrent.endsWith("type=HostOnly", Utf8Str::CaseInsensitive))
2550 {
2551 /* Attach to the right interface */
2552 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_HostOnly);
2553 if (FAILED(rc)) throw rc;
2554 ComPtr<IHost> host;
2555 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
2556 if (FAILED(rc)) throw rc;
2557 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
2558 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
2559 if (FAILED(rc)) throw rc;
2560 // We search for the first host network interface which
2561 // is usable for host only networking
2562 for (size_t j = 0;
2563 j < nwInterfaces.size();
2564 ++j)
2565 {
2566 HostNetworkInterfaceType_T itype;
2567 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
2568 if (FAILED(rc)) throw rc;
2569 if (itype == HostNetworkInterfaceType_HostOnly)
2570 {
2571 Bstr name;
2572 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
2573 if (FAILED(rc)) throw rc;
2574 /* Set the interface name to attach to */
2575 rc = pNetworkAdapter->COMSETTER(HostOnlyInterface)(name.raw());
2576 if (FAILED(rc)) throw rc;
2577 break;
2578 }
2579 }
2580 }
2581 /* Next test for internal interfaces */
2582 else if (pvsys->strExtraConfigCurrent.endsWith("type=Internal", Utf8Str::CaseInsensitive))
2583 {
2584 /* Attach to the right interface */
2585 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_Internal);
2586 if (FAILED(rc)) throw rc;
2587 }
2588 /* Next test for Generic interfaces */
2589 else if (pvsys->strExtraConfigCurrent.endsWith("type=Generic", Utf8Str::CaseInsensitive))
2590 {
2591 /* Attach to the right interface */
2592 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_Generic);
2593 if (FAILED(rc)) throw rc;
2594 }
2595
2596 /* Next test for NAT network interfaces */
2597 else if (pvsys->strExtraConfigCurrent.endsWith("type=NATNetwork", Utf8Str::CaseInsensitive))
2598 {
2599 /* Attach to the right interface */
2600 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_NATNetwork);
2601 if (FAILED(rc)) throw rc;
2602 com::SafeIfaceArray<INATNetwork> nwNATNetworks;
2603 rc = mVirtualBox->COMGETTER(NATNetworks)(ComSafeArrayAsOutParam(nwNATNetworks));
2604 if (FAILED(rc)) throw rc;
2605 // Pick the first NAT network (if there is any)
2606 if (nwNATNetworks.size())
2607 {
2608 Bstr name;
2609 rc = nwNATNetworks[0]->COMGETTER(NetworkName)(name.asOutParam());
2610 if (FAILED(rc)) throw rc;
2611 /* Set the NAT network name to attach to */
2612 rc = pNetworkAdapter->COMSETTER(NATNetwork)(name.raw());
2613 if (FAILED(rc)) throw rc;
2614 break;
2615 }
2616 }
2617 }
2618 }
2619
2620 // IDE Hard disk controller
2621 std::list<VirtualSystemDescriptionEntry*> vsdeHDCIDE =
2622 vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskControllerIDE);
2623 /*
2624 * In OVF (at least VMware's version of it), an IDE controller has two ports,
2625 * so VirtualBox's single IDE controller with two channels and two ports each counts as
2626 * two OVF IDE controllers -- so we accept one or two such IDE controllers
2627 */
2628 size_t cIDEControllers = vsdeHDCIDE.size();
2629 if (cIDEControllers > 2)
2630 throw setError(VBOX_E_FILE_ERROR,
2631 tr("Too many IDE controllers in OVF; import facility only supports two"));
2632 if (!vsdeHDCIDE.empty())
2633 {
2634 // one or two IDE controllers present in OVF: add one VirtualBox controller
2635 ComPtr<IStorageController> pController;
2636 rc = pNewMachine->AddStorageController(Bstr("IDE Controller").raw(), StorageBus_IDE, pController.asOutParam());
2637 if (FAILED(rc)) throw rc;
2638
2639 const char *pcszIDEType = vsdeHDCIDE.front()->strVBoxCurrent.c_str();
2640 if (!strcmp(pcszIDEType, "PIIX3"))
2641 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX3);
2642 else if (!strcmp(pcszIDEType, "PIIX4"))
2643 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX4);
2644 else if (!strcmp(pcszIDEType, "ICH6"))
2645 rc = pController->COMSETTER(ControllerType)(StorageControllerType_ICH6);
2646 else
2647 throw setError(VBOX_E_FILE_ERROR,
2648 tr("Invalid IDE controller type \"%s\""),
2649 pcszIDEType);
2650 if (FAILED(rc)) throw rc;
2651 }
2652
2653 /* Hard disk controller SATA */
2654 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSATA =
2655 vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskControllerSATA);
2656 if (vsdeHDCSATA.size() > 1)
2657 throw setError(VBOX_E_FILE_ERROR,
2658 tr("Too many SATA controllers in OVF; import facility only supports one"));
2659 if (!vsdeHDCSATA.empty())
2660 {
2661 ComPtr<IStorageController> pController;
2662 const Utf8Str &hdcVBox = vsdeHDCSATA.front()->strVBoxCurrent;
2663 if (hdcVBox == "AHCI")
2664 {
2665 rc = pNewMachine->AddStorageController(Bstr("SATA Controller").raw(),
2666 StorageBus_SATA,
2667 pController.asOutParam());
2668 if (FAILED(rc)) throw rc;
2669 }
2670 else
2671 throw setError(VBOX_E_FILE_ERROR,
2672 tr("Invalid SATA controller type \"%s\""),
2673 hdcVBox.c_str());
2674 }
2675
2676 /* Hard disk controller SCSI */
2677 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSCSI =
2678 vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskControllerSCSI);
2679 if (vsdeHDCSCSI.size() > 1)
2680 throw setError(VBOX_E_FILE_ERROR,
2681 tr("Too many SCSI controllers in OVF; import facility only supports one"));
2682 if (!vsdeHDCSCSI.empty())
2683 {
2684 ComPtr<IStorageController> pController;
2685 Bstr bstrName(L"SCSI Controller");
2686 StorageBus_T busType = StorageBus_SCSI;
2687 StorageControllerType_T controllerType;
2688 const Utf8Str &hdcVBox = vsdeHDCSCSI.front()->strVBoxCurrent;
2689 if (hdcVBox == "LsiLogic")
2690 controllerType = StorageControllerType_LsiLogic;
2691 else if (hdcVBox == "LsiLogicSas")
2692 {
2693 // OVF treats LsiLogicSas as a SCSI controller but VBox considers it a class of its own
2694 bstrName = L"SAS Controller";
2695 busType = StorageBus_SAS;
2696 controllerType = StorageControllerType_LsiLogicSas;
2697 }
2698 else if (hdcVBox == "BusLogic")
2699 controllerType = StorageControllerType_BusLogic;
2700 else
2701 throw setError(VBOX_E_FILE_ERROR,
2702 tr("Invalid SCSI controller type \"%s\""),
2703 hdcVBox.c_str());
2704
2705 rc = pNewMachine->AddStorageController(bstrName.raw(), busType, pController.asOutParam());
2706 if (FAILED(rc)) throw rc;
2707 rc = pController->COMSETTER(ControllerType)(controllerType);
2708 if (FAILED(rc)) throw rc;
2709 }
2710
2711 /* Hard disk controller SAS */
2712 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSAS =
2713 vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskControllerSAS);
2714 if (vsdeHDCSAS.size() > 1)
2715 throw setError(VBOX_E_FILE_ERROR,
2716 tr("Too many SAS controllers in OVF; import facility only supports one"));
2717 if (!vsdeHDCSAS.empty())
2718 {
2719 ComPtr<IStorageController> pController;
2720 rc = pNewMachine->AddStorageController(Bstr(L"SAS Controller").raw(),
2721 StorageBus_SAS,
2722 pController.asOutParam());
2723 if (FAILED(rc)) throw rc;
2724 rc = pController->COMSETTER(ControllerType)(StorageControllerType_LsiLogicSas);
2725 if (FAILED(rc)) throw rc;
2726 }
2727
2728 /* Now its time to register the machine before we add any hard disks */
2729 rc = mVirtualBox->RegisterMachine(pNewMachine);
2730 if (FAILED(rc)) throw rc;
2731
2732 // store new machine for roll-back in case of errors
2733 Bstr bstrNewMachineId;
2734 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
2735 if (FAILED(rc)) throw rc;
2736 Guid uuidNewMachine(bstrNewMachineId);
2737 m->llGuidsMachinesCreated.push_back(uuidNewMachine);
2738
2739 // Add floppies and CD-ROMs to the appropriate controllers.
2740 std::list<VirtualSystemDescriptionEntry*> vsdeFloppy = vsdescThis->i_findByType(VirtualSystemDescriptionType_Floppy);
2741 if (vsdeFloppy.size() > 1)
2742 throw setError(VBOX_E_FILE_ERROR,
2743 tr("Too many floppy controllers in OVF; import facility only supports one"));
2744 std::list<VirtualSystemDescriptionEntry*> vsdeCDROM = vsdescThis->i_findByType(VirtualSystemDescriptionType_CDROM);
2745 if ( !vsdeFloppy.empty()
2746 || !vsdeCDROM.empty()
2747 )
2748 {
2749 // If there's an error here we need to close the session, so
2750 // we need another try/catch block.
2751
2752 try
2753 {
2754 // to attach things we need to open a session for the new machine
2755 rc = pNewMachine->LockMachine(stack.pSession, LockType_Write);
2756 if (FAILED(rc)) throw rc;
2757 stack.fSessionOpen = true;
2758
2759 ComPtr<IMachine> sMachine;
2760 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
2761 if (FAILED(rc)) throw rc;
2762
2763 // floppy first
2764 if (vsdeFloppy.size() == 1)
2765 {
2766 ComPtr<IStorageController> pController;
2767 rc = sMachine->AddStorageController(Bstr("Floppy Controller").raw(),
2768 StorageBus_Floppy,
2769 pController.asOutParam());
2770 if (FAILED(rc)) throw rc;
2771
2772 Bstr bstrName;
2773 rc = pController->COMGETTER(Name)(bstrName.asOutParam());
2774 if (FAILED(rc)) throw rc;
2775
2776 // this is for rollback later
2777 MyHardDiskAttachment mhda;
2778 mhda.pMachine = pNewMachine;
2779 mhda.controllerType = bstrName;
2780 mhda.lControllerPort = 0;
2781 mhda.lDevice = 0;
2782
2783 Log(("Attaching floppy\n"));
2784
2785 rc = sMachine->AttachDevice(mhda.controllerType.raw(),
2786 mhda.lControllerPort,
2787 mhda.lDevice,
2788 DeviceType_Floppy,
2789 NULL);
2790 if (FAILED(rc)) throw rc;
2791
2792 stack.llHardDiskAttachments.push_back(mhda);
2793 }
2794
2795 rc = sMachine->SaveSettings();
2796 if (FAILED(rc)) throw rc;
2797
2798 // only now that we're done with all disks, close the session
2799 rc = stack.pSession->UnlockMachine();
2800 if (FAILED(rc)) throw rc;
2801 stack.fSessionOpen = false;
2802 }
2803 catch(HRESULT aRC)
2804 {
2805 com::ErrorInfo info;
2806
2807 if (stack.fSessionOpen)
2808 stack.pSession->UnlockMachine();
2809
2810 if (info.isFullAvailable())
2811 throw setError(aRC, Utf8Str(info.getText()).c_str());
2812 else
2813 throw setError(aRC, "Unknown error during OVF import");
2814 }
2815 }
2816
2817 // create the hard disks & connect them to the appropriate controllers
2818 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskImage);
2819 if (!avsdeHDs.empty())
2820 {
2821 // If there's an error here we need to close the session, so
2822 // we need another try/catch block.
2823 try
2824 {
2825#ifdef LOG_ENABLED
2826 if (LogIsEnabled())
2827 {
2828 size_t i = 0;
2829 for (list<VirtualSystemDescriptionEntry*>::const_iterator itHD = avsdeHDs.begin();
2830 itHD != avsdeHDs.end(); ++itHD, i++)
2831 Log(("avsdeHDs[%zu]: strRef=%s strOvf=%s\n", i, (*itHD)->strRef.c_str(), (*itHD)->strOvf.c_str()));
2832 i = 0;
2833 for (ovf::DiskImagesMap::const_iterator itDisk = stack.mapDisks.begin(); itDisk != stack.mapDisks.end(); ++itDisk)
2834 Log(("mapDisks[%zu]: strDiskId=%s strHref=%s\n",
2835 i, itDisk->second.strDiskId.c_str(), itDisk->second.strHref.c_str()));
2836
2837 }
2838#endif
2839
2840 // to attach things we need to open a session for the new machine
2841 rc = pNewMachine->LockMachine(stack.pSession, LockType_Write);
2842 if (FAILED(rc)) throw rc;
2843 stack.fSessionOpen = true;
2844
2845 /* get VM name from virtual system description. Only one record is possible (size of list is equal 1). */
2846 std::list<VirtualSystemDescriptionEntry*> vmName = vsdescThis->i_findByType(VirtualSystemDescriptionType_Name);
2847 std::list<VirtualSystemDescriptionEntry*>::iterator vmNameIt = vmName.begin();
2848 VirtualSystemDescriptionEntry* vmNameEntry = *vmNameIt;
2849
2850
2851 ovf::DiskImagesMap::const_iterator oit = stack.mapDisks.begin();
2852 std::set<RTCString> disksResolvedNames;
2853
2854 uint32_t cImportedDisks = 0;
2855
2856 while (oit != stack.mapDisks.end() && cImportedDisks != avsdeHDs.size())
2857 {
2858 ovf::DiskImage diCurrent = oit->second;
2859 ovf::VirtualDisksMap::const_iterator itVDisk = vsysThis.mapVirtualDisks.begin();
2860
2861 VirtualSystemDescriptionEntry *vsdeTargetHD = 0;
2862 Log(("diCurrent.strDiskId=%s diCurrent.strHref=%s\n", diCurrent.strDiskId.c_str(), diCurrent.strHref.c_str()));
2863
2864 /*
2865 *
2866 * Iterate over all given disk images of the virtual system
2867 * disks description. We need to find the target disk path,
2868 * which could be changed by the user.
2869 *
2870 */
2871 {
2872 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
2873 for (itHD = avsdeHDs.begin();
2874 itHD != avsdeHDs.end();
2875 ++itHD)
2876 {
2877 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
2878 if (vsdeHD->strRef == diCurrent.strDiskId)
2879 {
2880 vsdeTargetHD = vsdeHD;
2881 break;
2882 }
2883 }
2884 if (!vsdeTargetHD)
2885 {
2886 /* possible case if a disk image belongs to other virtual system (OVF package with multiple VMs inside) */
2887 Log1Warning(("OVA/OVF import: Disk image %s was missed during import of VM %s\n",
2888 oit->first.c_str(), vmNameEntry->strOvf.c_str()));
2889 NOREF(vmNameEntry);
2890 ++oit;
2891 continue;
2892 }
2893
2894 //diCurrent.strDiskId contains the disk identifier (e.g. "vmdisk1"), which should exist
2895 //in the virtual system's disks map under that ID and also in the global images map
2896 itVDisk = vsysThis.mapVirtualDisks.find(diCurrent.strDiskId);
2897 if (itVDisk == vsysThis.mapVirtualDisks.end())
2898 throw setError(E_FAIL,
2899 tr("Internal inconsistency looking up disk image '%s'"),
2900 diCurrent.strHref.c_str());
2901 }
2902
2903 /*
2904 * preliminary check availability of the image
2905 * This step is useful if image is placed in the OVA (TAR) package
2906 */
2907
2908 Utf8Str name = i_applianceIOName(applianceIOTar);
2909
2910 if (strncmp(pStorage->pVDImageIfaces->pszInterfaceName, name.c_str(), name.length()) == 0)
2911 {
2912 /* It means that we possibly have imported the storage earlier on the previous loop steps*/
2913 std::set<RTCString>::const_iterator h = disksResolvedNames.find(diCurrent.strHref);
2914 if (h != disksResolvedNames.end())
2915 {
2916 /* Yes, disk name was found, we can skip it*/
2917 ++oit;
2918 continue;
2919 }
2920
2921 RTCString availableImage(diCurrent.strHref);
2922
2923 rc = i_preCheckImageAvailability(pStorage, availableImage);
2924
2925 if (SUCCEEDED(rc))
2926 {
2927 /* current opened file isn't the same as passed one */
2928 if (availableImage.compare(diCurrent.strHref, Utf8Str::CaseInsensitive) != 0)
2929 {
2930 /*
2931 * availableImage contains the disk file reference (e.g. "disk1.vmdk"), which should exist
2932 * in the global images map.
2933 * And find the disk from the OVF's disk list
2934 *
2935 */
2936 {
2937 ovf::DiskImagesMap::const_iterator itDiskImage = stack.mapDisks.begin();
2938 while (++itDiskImage != stack.mapDisks.end())
2939 {
2940 if (itDiskImage->second.strHref.compare(availableImage, Utf8Str::CaseInsensitive) == 0)
2941 break;
2942 }
2943 if (itDiskImage == stack.mapDisks.end())
2944 {
2945 throw setError(E_FAIL,
2946 tr("Internal inconsistency looking up disk image '%s'. "
2947 "Check compliance OVA package structure and file names "
2948 "references in the section <References> in the OVF file."),
2949 availableImage.c_str());
2950 }
2951
2952 /* replace with a new found disk image */
2953 diCurrent = *(&itDiskImage->second);
2954 }
2955
2956 /*
2957 * Again iterate over all given disk images of the virtual system
2958 * disks description using the found disk image
2959 */
2960 {
2961 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
2962 for (itHD = avsdeHDs.begin();
2963 itHD != avsdeHDs.end();
2964 ++itHD)
2965 {
2966 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
2967 if (vsdeHD->strRef == diCurrent.strDiskId)
2968 {
2969 vsdeTargetHD = vsdeHD;
2970 break;
2971 }
2972 }
2973 if (!vsdeTargetHD)
2974 {
2975 /*
2976 * in this case it's an error because something wrong with OVF description file.
2977 * May be VBox imports OVA package with wrong file sequence inside the archive.
2978 */
2979 throw setError(E_FAIL,
2980 tr("Internal inconsistency looking up disk image '%s'"),
2981 diCurrent.strHref.c_str());
2982 }
2983
2984 itVDisk = vsysThis.mapVirtualDisks.find(diCurrent.strDiskId);
2985 if (itVDisk == vsysThis.mapVirtualDisks.end())
2986 throw setError(E_FAIL,
2987 tr("Internal inconsistency looking up disk image '%s'"),
2988 diCurrent.strHref.c_str());
2989 }
2990 }
2991 else
2992 {
2993 ++oit;
2994 }
2995 }
2996 else
2997 {
2998 ++oit;
2999 continue;
3000 }
3001 }
3002 else
3003 {
3004 /* just continue with normal files*/
3005 ++oit;
3006 }
3007
3008 const ovf::VirtualDisk &ovfVdisk = itVDisk->second;
3009
3010 /* very important to store disk name for the next checks */
3011 disksResolvedNames.insert(diCurrent.strHref);
3012
3013 ComObjPtr<Medium> pTargetHD;
3014
3015 Utf8Str savedVBoxCurrent = vsdeTargetHD->strVBoxCurrent;
3016
3017 i_importOneDiskImage(diCurrent,
3018 &vsdeTargetHD->strVBoxCurrent,
3019 pTargetHD,
3020 stack,
3021 pCallbacks,
3022 pStorage);
3023
3024 // now use the new uuid to attach the disk image to our new machine
3025 ComPtr<IMachine> sMachine;
3026 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
3027 if (FAILED(rc))
3028 throw rc;
3029
3030 // find the hard disk controller to which we should attach
3031 ovf::HardDiskController hdc = (*vsysThis.mapControllers.find(ovfVdisk.idController)).second;
3032
3033 // this is for rollback later
3034 MyHardDiskAttachment mhda;
3035 mhda.pMachine = pNewMachine;
3036
3037 i_convertDiskAttachmentValues(hdc,
3038 ovfVdisk.ulAddressOnParent,
3039 mhda.controllerType, // Bstr
3040 mhda.lControllerPort,
3041 mhda.lDevice);
3042
3043 Log(("Attaching disk %s to port %d on device %d\n",
3044 vsdeTargetHD->strVBoxCurrent.c_str(), mhda.lControllerPort, mhda.lDevice));
3045
3046 ComObjPtr<MediumFormat> mediumFormat;
3047 rc = i_findMediumFormatFromDiskImage(diCurrent, mediumFormat);
3048 if (FAILED(rc))
3049 throw rc;
3050
3051 Bstr bstrFormatName;
3052 rc = mediumFormat->COMGETTER(Name)(bstrFormatName.asOutParam());
3053 if (FAILED(rc))
3054 throw rc;
3055
3056 Utf8Str vdf = Utf8Str(bstrFormatName);
3057
3058 if (vdf.compare("RAW", Utf8Str::CaseInsensitive) == 0)
3059 {
3060 ComPtr<IMedium> dvdImage(pTargetHD);
3061
3062 rc = mVirtualBox->OpenMedium(Bstr(vsdeTargetHD->strVBoxCurrent).raw(),
3063 DeviceType_DVD,
3064 AccessMode_ReadWrite,
3065 false,
3066 dvdImage.asOutParam());
3067
3068 if (FAILED(rc))
3069 throw rc;
3070
3071 rc = sMachine->AttachDevice(mhda.controllerType.raw(),// wstring name
3072 mhda.lControllerPort, // long controllerPort
3073 mhda.lDevice, // long device
3074 DeviceType_DVD, // DeviceType_T type
3075 dvdImage);
3076 if (FAILED(rc))
3077 throw rc;
3078 }
3079 else
3080 {
3081 rc = sMachine->AttachDevice(mhda.controllerType.raw(),// wstring name
3082 mhda.lControllerPort, // long controllerPort
3083 mhda.lDevice, // long device
3084 DeviceType_HardDisk, // DeviceType_T type
3085 pTargetHD);
3086
3087 if (FAILED(rc))
3088 throw rc;
3089 }
3090
3091 stack.llHardDiskAttachments.push_back(mhda);
3092
3093 rc = sMachine->SaveSettings();
3094 if (FAILED(rc))
3095 throw rc;
3096
3097 /* restore */
3098 vsdeTargetHD->strVBoxCurrent = savedVBoxCurrent;
3099
3100 ++cImportedDisks;
3101
3102 } // end while(oit != stack.mapDisks.end())
3103
3104 /*
3105 * quantity of the imported disks isn't equal to the size of the avsdeHDs list.
3106 */
3107 if(cImportedDisks < avsdeHDs.size())
3108 {
3109 Log1Warning(("Not all disk images were imported for VM %s. Check OVF description file.",
3110 vmNameEntry->strOvf.c_str()));
3111 }
3112
3113 // only now that we're done with all disks, close the session
3114 rc = stack.pSession->UnlockMachine();
3115 if (FAILED(rc))
3116 throw rc;
3117 stack.fSessionOpen = false;
3118 }
3119 catch(HRESULT aRC)
3120 {
3121 com::ErrorInfo info;
3122 if (stack.fSessionOpen)
3123 stack.pSession->UnlockMachine();
3124
3125 if (info.isFullAvailable())
3126 throw setError(aRC, Utf8Str(info.getText()).c_str());
3127 else
3128 throw setError(aRC, "Unknown error during OVF import");
3129 }
3130 }
3131 LogFlowFuncLeave();
3132}
3133
3134/**
3135 * Imports one OVF virtual system (described by a vbox:Machine tag represented by the given config
3136 * structure) into VirtualBox by creating an IMachine instance, which is returned.
3137 *
3138 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
3139 * up any leftovers from this function. For this, the given ImportStack instance has received information
3140 * about what needs cleaning up (to support rollback).
3141 *
3142 * The machine config stored in the settings::MachineConfigFile structure contains the UUIDs of
3143 * the disk attachments used by the machine when it was exported. We also add vbox:uuid attributes
3144 * to the OVF disks sections so we can look them up. While importing these UUIDs into a second host
3145 * will most probably work, reimporting them into the same host will cause conflicts, so we always
3146 * generate new ones on import. This involves the following:
3147 *
3148 * 1) Scan the machine config for disk attachments.
3149 *
3150 * 2) For each disk attachment found, look up the OVF disk image from the disk references section
3151 * and import the disk into VirtualBox, which creates a new UUID for it. In the machine config,
3152 * replace the old UUID with the new one.
3153 *
3154 * 3) Change the machine config according to the OVF virtual system descriptions, in case the
3155 * caller has modified them using setFinalValues().
3156 *
3157 * 4) Create the VirtualBox machine with the modfified machine config.
3158 *
3159 * @param config
3160 * @param pNewMachine
3161 * @param stack
3162 */
3163void Appliance::i_importVBoxMachine(ComObjPtr<VirtualSystemDescription> &vsdescThis,
3164 ComPtr<IMachine> &pReturnNewMachine,
3165 ImportStack &stack,
3166 PVDINTERFACEIO pCallbacks,
3167 PSHASTORAGE pStorage)
3168{
3169 LogFlowFuncEnter();
3170 Assert(vsdescThis->m->pConfig);
3171
3172 HRESULT rc = S_OK;
3173
3174 settings::MachineConfigFile &config = *vsdescThis->m->pConfig;
3175
3176 /*
3177 * step 1): modify machine config according to OVF config, in case the user
3178 * has modified them using setFinalValues()
3179 */
3180
3181 /* OS Type */
3182 config.machineUserData.strOsType = stack.strOsTypeVBox;
3183 /* Description */
3184 config.machineUserData.strDescription = stack.strDescription;
3185 /* CPU count & extented attributes */
3186 config.hardwareMachine.cCPUs = stack.cCPUs;
3187 if (stack.fForceIOAPIC)
3188 config.hardwareMachine.fHardwareVirt = true;
3189 if (stack.fForceIOAPIC)
3190 config.hardwareMachine.biosSettings.fIOAPICEnabled = true;
3191 /* RAM size */
3192 config.hardwareMachine.ulMemorySizeMB = stack.ulMemorySizeMB;
3193
3194/*
3195 <const name="HardDiskControllerIDE" value="14" />
3196 <const name="HardDiskControllerSATA" value="15" />
3197 <const name="HardDiskControllerSCSI" value="16" />
3198 <const name="HardDiskControllerSAS" value="17" />
3199*/
3200
3201#ifdef VBOX_WITH_USB
3202 /* USB controller */
3203 if (stack.fUSBEnabled)
3204 {
3205 /** @todo r=klaus add support for arbitrary USB controller types, this can't handle
3206 * multiple controllers due to its design anyway */
3207 /* usually the OHCI controller is enabled already, need to check */
3208 bool fOHCIEnabled = false;
3209 settings::USBControllerList &llUSBControllers = config.hardwareMachine.usbSettings.llUSBControllers;
3210 settings::USBControllerList::iterator it;
3211 for (it = llUSBControllers.begin(); it != llUSBControllers.end(); ++it)
3212 {
3213 if (it->enmType == USBControllerType_OHCI)
3214 {
3215 fOHCIEnabled = true;
3216 break;
3217 }
3218 }
3219
3220 if (!fOHCIEnabled)
3221 {
3222 settings::USBController ctrl;
3223 ctrl.strName = "OHCI";
3224 ctrl.enmType = USBControllerType_OHCI;
3225
3226 llUSBControllers.push_back(ctrl);
3227 }
3228 }
3229 else
3230 config.hardwareMachine.usbSettings.llUSBControllers.clear();
3231#endif
3232 /* Audio adapter */
3233 if (stack.strAudioAdapter.isNotEmpty())
3234 {
3235 config.hardwareMachine.audioAdapter.fEnabled = true;
3236 config.hardwareMachine.audioAdapter.controllerType = (AudioControllerType_T)stack.strAudioAdapter.toUInt32();
3237 }
3238 else
3239 config.hardwareMachine.audioAdapter.fEnabled = false;
3240 /* Network adapter */
3241 settings::NetworkAdaptersList &llNetworkAdapters = config.hardwareMachine.llNetworkAdapters;
3242 /* First disable all network cards, they will be enabled below again. */
3243 settings::NetworkAdaptersList::iterator it1;
3244 bool fKeepAllMACs = m->optListImport.contains(ImportOptions_KeepAllMACs);
3245 bool fKeepNATMACs = m->optListImport.contains(ImportOptions_KeepNATMACs);
3246 for (it1 = llNetworkAdapters.begin(); it1 != llNetworkAdapters.end(); ++it1)
3247 {
3248 it1->fEnabled = false;
3249 if (!( fKeepAllMACs
3250 || (fKeepNATMACs && it1->mode == NetworkAttachmentType_NAT)
3251 || (fKeepNATMACs && it1->mode == NetworkAttachmentType_NATNetwork)))
3252 Host::i_generateMACAddress(it1->strMACAddress);
3253 }
3254 /* Now iterate over all network entries. */
3255 std::list<VirtualSystemDescriptionEntry*> avsdeNWs = vsdescThis->i_findByType(VirtualSystemDescriptionType_NetworkAdapter);
3256 if (!avsdeNWs.empty())
3257 {
3258 /* Iterate through all network adapter entries and search for the
3259 * corresponding one in the machine config. If one is found, configure
3260 * it based on the user settings. */
3261 list<VirtualSystemDescriptionEntry*>::const_iterator itNW;
3262 for (itNW = avsdeNWs.begin();
3263 itNW != avsdeNWs.end();
3264 ++itNW)
3265 {
3266 VirtualSystemDescriptionEntry *vsdeNW = *itNW;
3267 if ( vsdeNW->strExtraConfigCurrent.startsWith("slot=", Utf8Str::CaseInsensitive)
3268 && vsdeNW->strExtraConfigCurrent.length() > 6)
3269 {
3270 uint32_t iSlot = vsdeNW->strExtraConfigCurrent.substr(5, 1).toUInt32();
3271 /* Iterate through all network adapters in the machine config. */
3272 for (it1 = llNetworkAdapters.begin();
3273 it1 != llNetworkAdapters.end();
3274 ++it1)
3275 {
3276 /* Compare the slots. */
3277 if (it1->ulSlot == iSlot)
3278 {
3279 it1->fEnabled = true;
3280 it1->type = (NetworkAdapterType_T)vsdeNW->strVBoxCurrent.toUInt32();
3281 break;
3282 }
3283 }
3284 }
3285 }
3286 }
3287
3288 /* Floppy controller */
3289 bool fFloppy = vsdescThis->i_findByType(VirtualSystemDescriptionType_Floppy).size() > 0;
3290 /* DVD controller */
3291 bool fDVD = vsdescThis->i_findByType(VirtualSystemDescriptionType_CDROM).size() > 0;
3292 /* Iterate over all storage controller check the attachments and remove
3293 * them when necessary. Also detect broken configs with more than one
3294 * attachment. Old VirtualBox versions (prior to 3.2.10) had all disk
3295 * attachments pointing to the last hard disk image, which causes import
3296 * failures. A long fixed bug, however the OVF files are long lived. */
3297 settings::StorageControllersList &llControllers = config.storageMachine.llStorageControllers;
3298 Guid hdUuid;
3299 uint32_t cDisks = 0;
3300 bool fInconsistent = false;
3301 bool fRepairDuplicate = false;
3302 settings::StorageControllersList::iterator it3;
3303 for (it3 = llControllers.begin();
3304 it3 != llControllers.end();
3305 ++it3)
3306 {
3307 settings::AttachedDevicesList &llAttachments = it3->llAttachedDevices;
3308 settings::AttachedDevicesList::iterator it4 = llAttachments.begin();
3309 while (it4 != llAttachments.end())
3310 {
3311 if ( ( !fDVD
3312 && it4->deviceType == DeviceType_DVD)
3313 ||
3314 ( !fFloppy
3315 && it4->deviceType == DeviceType_Floppy))
3316 {
3317 it4 = llAttachments.erase(it4);
3318 continue;
3319 }
3320 else if (it4->deviceType == DeviceType_HardDisk)
3321 {
3322 const Guid &thisUuid = it4->uuid;
3323 cDisks++;
3324 if (cDisks == 1)
3325 {
3326 if (hdUuid.isZero())
3327 hdUuid = thisUuid;
3328 else
3329 fInconsistent = true;
3330 }
3331 else
3332 {
3333 if (thisUuid.isZero())
3334 fInconsistent = true;
3335 else if (thisUuid == hdUuid)
3336 fRepairDuplicate = true;
3337 }
3338 }
3339 ++it4;
3340 }
3341 }
3342 /* paranoia... */
3343 if (fInconsistent || cDisks == 1)
3344 fRepairDuplicate = false;
3345
3346 /*
3347 * step 2: scan the machine config for media attachments
3348 */
3349 /* get VM name from virtual system description. Only one record is possible (size of list is equal 1). */
3350 std::list<VirtualSystemDescriptionEntry*> vmName = vsdescThis->i_findByType(VirtualSystemDescriptionType_Name);
3351 std::list<VirtualSystemDescriptionEntry*>::iterator vmNameIt = vmName.begin();
3352 VirtualSystemDescriptionEntry* vmNameEntry = *vmNameIt;
3353
3354 /* Get all hard disk descriptions. */
3355 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskImage);
3356 std::list<VirtualSystemDescriptionEntry*>::iterator avsdeHDsIt = avsdeHDs.begin();
3357 /* paranoia - if there is no 1:1 match do not try to repair. */
3358 if (cDisks != avsdeHDs.size())
3359 fRepairDuplicate = false;
3360
3361 // there must be an image in the OVF disk structs with the same UUID
3362
3363 ovf::DiskImagesMap::const_iterator oit = stack.mapDisks.begin();
3364 std::set<RTCString> disksResolvedNames;
3365
3366 uint32_t cImportedDisks = 0;
3367
3368 while(oit != stack.mapDisks.end() && cImportedDisks != avsdeHDs.size())
3369 {
3370 ovf::DiskImage diCurrent = oit->second;
3371
3372 VirtualSystemDescriptionEntry *vsdeTargetHD = 0;
3373
3374 {
3375 /* Iterate over all given disk images of the virtual system
3376 * disks description. We need to find the target disk path,
3377 * which could be changed by the user. */
3378 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
3379 for (itHD = avsdeHDs.begin();
3380 itHD != avsdeHDs.end();
3381 ++itHD)
3382 {
3383 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
3384 if (vsdeHD->strRef == oit->first)
3385 {
3386 vsdeTargetHD = vsdeHD;
3387 break;
3388 }
3389 }
3390 if (!vsdeTargetHD)
3391 {
3392 /* possible case if a disk image belongs to other virtual system (OVF package with multiple VMs inside) */
3393 Log1Warning(("OVA/OVF import: Disk image %s was missed during import of VM %s\n",
3394 oit->first.c_str(), vmNameEntry->strOvf.c_str()));
3395 NOREF(vmNameEntry);
3396 ++oit;
3397 continue;
3398 }
3399 }
3400
3401 /*
3402 * preliminary check availability of the image
3403 * This step is useful if image is placed in the OVA (TAR) package
3404 */
3405
3406 Utf8Str name = i_applianceIOName(applianceIOTar);
3407
3408 if (strncmp(pStorage->pVDImageIfaces->pszInterfaceName, name.c_str(), name.length()) == 0)
3409 {
3410 /* It means that we possibly have imported the storage earlier on the previous loop steps*/
3411 std::set<RTCString>::const_iterator h = disksResolvedNames.find(diCurrent.strHref);
3412 if (h != disksResolvedNames.end())
3413 {
3414 /* Yes, disk name was found, we can skip it*/
3415 ++oit;
3416 continue;
3417 }
3418
3419 RTCString availableImage(diCurrent.strHref);
3420
3421 rc = i_preCheckImageAvailability(pStorage, availableImage);
3422
3423 if (SUCCEEDED(rc))
3424 {
3425 /* current opened file isn't the same as passed one */
3426 if(availableImage.compare(diCurrent.strHref, Utf8Str::CaseInsensitive) != 0)
3427 {
3428 // availableImage contains the disk identifier (e.g. "vmdisk1"), which should exist
3429 // in the virtual system's disks map under that ID and also in the global images map
3430 // and find the disk from the OVF's disk list
3431 ovf::DiskImagesMap::const_iterator itDiskImage = stack.mapDisks.begin();
3432 while (++itDiskImage != stack.mapDisks.end())
3433 {
3434 if(itDiskImage->second.strHref.compare(availableImage, Utf8Str::CaseInsensitive) == 0 )
3435 break;
3436 }
3437 if (itDiskImage == stack.mapDisks.end())
3438 {
3439 throw setError(E_FAIL,
3440 tr("Internal inconsistency looking up disk image '%s'. "
3441 "Check compliance OVA package structure and file names "
3442 "references in the section <References> in the OVF file."),
3443 availableImage.c_str());
3444 }
3445
3446 /* replace with a new found disk image */
3447 diCurrent = *(&itDiskImage->second);
3448
3449 /*
3450 * Again iterate over all given disk images of the virtual system
3451 * disks description using the found disk image
3452 */
3453 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
3454 for (itHD = avsdeHDs.begin();
3455 itHD != avsdeHDs.end();
3456 ++itHD)
3457 {
3458 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
3459 if (vsdeHD->strRef == diCurrent.strDiskId)
3460 {
3461 vsdeTargetHD = vsdeHD;
3462 break;
3463 }
3464 }
3465 if (!vsdeTargetHD)
3466 /*
3467 * in this case it's an error because something wrong with OVF description file.
3468 * May be VBox imports OVA package with wrong file sequence inside the archive.
3469 */
3470 throw setError(E_FAIL,
3471 tr("Internal inconsistency looking up disk image '%s'"),
3472 diCurrent.strHref.c_str());
3473 }
3474 else
3475 {
3476 ++oit;
3477 }
3478 }
3479 else
3480 {
3481 ++oit;
3482 continue;
3483 }
3484 }
3485 else
3486 {
3487 /* just continue with normal files*/
3488 ++oit;
3489 }
3490
3491 /* Important! to store disk name for the next checks */
3492 disksResolvedNames.insert(diCurrent.strHref);
3493
3494 // there must be an image in the OVF disk structs with the same UUID
3495 bool fFound = false;
3496 Utf8Str strUuid;
3497
3498 // for each storage controller...
3499 for (settings::StorageControllersList::iterator sit = config.storageMachine.llStorageControllers.begin();
3500 sit != config.storageMachine.llStorageControllers.end();
3501 ++sit)
3502 {
3503 settings::StorageController &sc = *sit;
3504
3505 // find the OVF virtual system description entry for this storage controller
3506 switch (sc.storageBus)
3507 {
3508 case StorageBus_SATA:
3509 break;
3510 case StorageBus_SCSI:
3511 break;
3512 case StorageBus_IDE:
3513 break;
3514 case StorageBus_SAS:
3515 break;
3516 }
3517
3518 // for each medium attachment to this controller...
3519 for (settings::AttachedDevicesList::iterator dit = sc.llAttachedDevices.begin();
3520 dit != sc.llAttachedDevices.end();
3521 ++dit)
3522 {
3523 settings::AttachedDevice &d = *dit;
3524
3525 if (d.uuid.isZero())
3526 // empty DVD and floppy media
3527 continue;
3528
3529 // When repairing a broken VirtualBox xml config section (written
3530 // by VirtualBox versions earlier than 3.2.10) assume the disks
3531 // show up in the same order as in the OVF description.
3532 if (fRepairDuplicate)
3533 {
3534 VirtualSystemDescriptionEntry *vsdeHD = *avsdeHDsIt;
3535 ovf::DiskImagesMap::const_iterator itDiskImage = stack.mapDisks.find(vsdeHD->strRef);
3536 if (itDiskImage != stack.mapDisks.end())
3537 {
3538 const ovf::DiskImage &di = itDiskImage->second;
3539 d.uuid = Guid(di.uuidVBox);
3540 }
3541 ++avsdeHDsIt;
3542 }
3543
3544 // convert the Guid to string
3545 strUuid = d.uuid.toString();
3546
3547 if (diCurrent.uuidVBox != strUuid)
3548 {
3549 continue;
3550 }
3551
3552 /*
3553 * step 3: import disk
3554 */
3555 Utf8Str savedVBoxCurrent = vsdeTargetHD->strVBoxCurrent;
3556 ComObjPtr<Medium> pTargetHD;
3557
3558 i_importOneDiskImage(diCurrent,
3559 &vsdeTargetHD->strVBoxCurrent,
3560 pTargetHD,
3561 stack,
3562 pCallbacks,
3563 pStorage);
3564
3565 Bstr hdId;
3566
3567 ComObjPtr<MediumFormat> mediumFormat;
3568 rc = i_findMediumFormatFromDiskImage(diCurrent, mediumFormat);
3569 if (FAILED(rc))
3570 throw rc;
3571
3572 Bstr bstrFormatName;
3573 rc = mediumFormat->COMGETTER(Name)(bstrFormatName.asOutParam());
3574 if (FAILED(rc))
3575 throw rc;
3576
3577 Utf8Str vdf = Utf8Str(bstrFormatName);
3578
3579 if (vdf.compare("RAW", Utf8Str::CaseInsensitive) == 0)
3580 {
3581 ComPtr<IMedium> dvdImage(pTargetHD);
3582
3583 rc = mVirtualBox->OpenMedium(Bstr(vsdeTargetHD->strVBoxCurrent).raw(),
3584 DeviceType_DVD,
3585 AccessMode_ReadWrite,
3586 false,
3587 dvdImage.asOutParam());
3588
3589 if (FAILED(rc)) throw rc;
3590
3591 // ... and replace the old UUID in the machine config with the one of
3592 // the imported disk that was just created
3593 rc = dvdImage->COMGETTER(Id)(hdId.asOutParam());
3594 if (FAILED(rc)) throw rc;
3595 }
3596 else
3597 {
3598 // ... and replace the old UUID in the machine config with the one of
3599 // the imported disk that was just created
3600 rc = pTargetHD->COMGETTER(Id)(hdId.asOutParam());
3601 if (FAILED(rc)) throw rc;
3602 }
3603
3604 /* restore */
3605 vsdeTargetHD->strVBoxCurrent = savedVBoxCurrent;
3606
3607 /*
3608 * 1. saving original UUID for restoring in case of failure.
3609 * 2. replacement of original UUID by new UUID in the current VM config (settings::MachineConfigFile).
3610 */
3611 {
3612 rc = stack.saveOriginalUUIDOfAttachedDevice(d, Utf8Str(hdId));
3613 d.uuid = hdId;
3614 }
3615
3616 fFound = true;
3617 break;
3618 } // for (settings::AttachedDevicesList::const_iterator dit = sc.llAttachedDevices.begin();
3619 } // for (settings::StorageControllersList::const_iterator sit = config.storageMachine.llStorageControllers.begin();
3620
3621 // no disk with such a UUID found:
3622 if (!fFound)
3623 throw setError(E_FAIL,
3624 tr("<vbox:Machine> element in OVF contains a medium attachment for the disk image %s "
3625 "but the OVF describes no such image"),
3626 strUuid.c_str());
3627
3628 ++cImportedDisks;
3629
3630 }// while(oit != stack.mapDisks.end())
3631
3632
3633 /*
3634 * quantity of the imported disks isn't equal to the size of the avsdeHDs list.
3635 */
3636 if(cImportedDisks < avsdeHDs.size())
3637 {
3638 Log1Warning(("Not all disk images were imported for VM %s. Check OVF description file.",
3639 vmNameEntry->strOvf.c_str()));
3640 }
3641
3642 /*
3643 * step 4): create the machine and have it import the config
3644 */
3645
3646 ComObjPtr<Machine> pNewMachine;
3647 rc = pNewMachine.createObject();
3648 if (FAILED(rc)) throw rc;
3649
3650 // this magic constructor fills the new machine object with the MachineConfig
3651 // instance that we created from the vbox:Machine
3652 rc = pNewMachine->init(mVirtualBox,
3653 stack.strNameVBox,// name from OVF preparations; can be suffixed to avoid duplicates
3654 config); // the whole machine config
3655 if (FAILED(rc)) throw rc;
3656
3657 pReturnNewMachine = ComPtr<IMachine>(pNewMachine);
3658
3659 // and register it
3660 rc = mVirtualBox->RegisterMachine(pNewMachine);
3661 if (FAILED(rc)) throw rc;
3662
3663 // store new machine for roll-back in case of errors
3664 Bstr bstrNewMachineId;
3665 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
3666 if (FAILED(rc)) throw rc;
3667 m->llGuidsMachinesCreated.push_back(Guid(bstrNewMachineId));
3668
3669 LogFlowFuncLeave();
3670}
3671
3672void Appliance::i_importMachines(ImportStack &stack,
3673 PVDINTERFACEIO pCallbacks,
3674 PSHASTORAGE pStorage)
3675{
3676 HRESULT rc = S_OK;
3677
3678 // this is safe to access because this thread only gets started
3679 const ovf::OVFReader &reader = *m->pReader;
3680
3681 /*
3682 * get the SHA digest version that was set in accordance with the value of attribute "xmlns:ovf"
3683 * of the element <Envelope> in the OVF file during reading operation. See readFSImpl().
3684 */
3685 pStorage->fSha256 = m->fSha256;
3686
3687 // create a session for the machine + disks we manipulate below
3688 rc = stack.pSession.createInprocObject(CLSID_Session);
3689 if (FAILED(rc)) throw rc;
3690
3691 list<ovf::VirtualSystem>::const_iterator it;
3692 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it1;
3693 /* Iterate through all virtual systems of that appliance */
3694 size_t i = 0;
3695 for (it = reader.m_llVirtualSystems.begin(), it1 = m->virtualSystemDescriptions.begin();
3696 it != reader.m_llVirtualSystems.end() && it1 != m->virtualSystemDescriptions.end();
3697 ++it, ++it1, ++i)
3698 {
3699 const ovf::VirtualSystem &vsysThis = *it;
3700 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it1);
3701
3702 ComPtr<IMachine> pNewMachine;
3703
3704 // there are two ways in which we can create a vbox machine from OVF:
3705 // -- either this OVF was written by vbox 3.2 or later, in which case there is a <vbox:Machine> element
3706 // in the <VirtualSystem>; then the VirtualSystemDescription::Data has a settings::MachineConfigFile
3707 // with all the machine config pretty-parsed;
3708 // -- or this is an OVF from an older vbox or an external source, and then we need to translate the
3709 // VirtualSystemDescriptionEntry and do import work
3710
3711 // Even for the vbox:Machine case, there are a number of configuration items that will be taken from
3712 // the OVF because otherwise the "override import parameters" mechanism in the GUI won't work.
3713
3714 // VM name
3715 std::list<VirtualSystemDescriptionEntry*> vsdeName = vsdescThis->i_findByType(VirtualSystemDescriptionType_Name);
3716 if (vsdeName.size() < 1)
3717 throw setError(VBOX_E_FILE_ERROR,
3718 tr("Missing VM name"));
3719 stack.strNameVBox = vsdeName.front()->strVBoxCurrent;
3720
3721 // have VirtualBox suggest where the filename would be placed so we can
3722 // put the disk images in the same directory
3723 Bstr bstrMachineFilename;
3724 rc = mVirtualBox->ComposeMachineFilename(Bstr(stack.strNameVBox).raw(),
3725 NULL /* aGroup */,
3726 NULL /* aCreateFlags */,
3727 NULL /* aBaseFolder */,
3728 bstrMachineFilename.asOutParam());
3729 if (FAILED(rc)) throw rc;
3730 // and determine the machine folder from that
3731 stack.strMachineFolder = bstrMachineFilename;
3732 stack.strMachineFolder.stripFilename();
3733 LogFunc(("i=%zu strName=%s bstrMachineFilename=%ls\n", i, stack.strNameVBox.c_str(), bstrMachineFilename.raw()));
3734
3735 // guest OS type
3736 std::list<VirtualSystemDescriptionEntry*> vsdeOS;
3737 vsdeOS = vsdescThis->i_findByType(VirtualSystemDescriptionType_OS);
3738 if (vsdeOS.size() < 1)
3739 throw setError(VBOX_E_FILE_ERROR,
3740 tr("Missing guest OS type"));
3741 stack.strOsTypeVBox = vsdeOS.front()->strVBoxCurrent;
3742
3743 // CPU count
3744 std::list<VirtualSystemDescriptionEntry*> vsdeCPU = vsdescThis->i_findByType(VirtualSystemDescriptionType_CPU);
3745 if (vsdeCPU.size() != 1)
3746 throw setError(VBOX_E_FILE_ERROR, tr("CPU count missing"));
3747
3748 stack.cCPUs = vsdeCPU.front()->strVBoxCurrent.toUInt32();
3749 // We need HWVirt & IO-APIC if more than one CPU is requested
3750 if (stack.cCPUs > 1)
3751 {
3752 stack.fForceHWVirt = true;
3753 stack.fForceIOAPIC = true;
3754 }
3755
3756 // RAM
3757 std::list<VirtualSystemDescriptionEntry*> vsdeRAM = vsdescThis->i_findByType(VirtualSystemDescriptionType_Memory);
3758 if (vsdeRAM.size() != 1)
3759 throw setError(VBOX_E_FILE_ERROR, tr("RAM size missing"));
3760 stack.ulMemorySizeMB = (ULONG)vsdeRAM.front()->strVBoxCurrent.toUInt64();
3761
3762#ifdef VBOX_WITH_USB
3763 // USB controller
3764 std::list<VirtualSystemDescriptionEntry*> vsdeUSBController =
3765 vsdescThis->i_findByType(VirtualSystemDescriptionType_USBController);
3766 // USB support is enabled if there's at least one such entry; to disable USB support,
3767 // the type of the USB item would have been changed to "ignore"
3768 stack.fUSBEnabled = !vsdeUSBController.empty();
3769#endif
3770 // audio adapter
3771 std::list<VirtualSystemDescriptionEntry*> vsdeAudioAdapter =
3772 vsdescThis->i_findByType(VirtualSystemDescriptionType_SoundCard);
3773 /* @todo: we support one audio adapter only */
3774 if (!vsdeAudioAdapter.empty())
3775 stack.strAudioAdapter = vsdeAudioAdapter.front()->strVBoxCurrent;
3776
3777 // for the description of the new machine, always use the OVF entry, the user may have changed it in the import config
3778 std::list<VirtualSystemDescriptionEntry*> vsdeDescription =
3779 vsdescThis->i_findByType(VirtualSystemDescriptionType_Description);
3780 if (!vsdeDescription.empty())
3781 stack.strDescription = vsdeDescription.front()->strVBoxCurrent;
3782
3783 // import vbox:machine or OVF now
3784 if (vsdescThis->m->pConfig)
3785 // vbox:Machine config
3786 i_importVBoxMachine(vsdescThis, pNewMachine, stack, pCallbacks, pStorage);
3787 else
3788 // generic OVF config
3789 i_importMachineGeneric(vsysThis, vsdescThis, pNewMachine, stack, pCallbacks, pStorage);
3790
3791 } // for (it = pAppliance->m->llVirtualSystems.begin() ...
3792}
3793
3794HRESULT Appliance::ImportStack::saveOriginalUUIDOfAttachedDevice(settings::AttachedDevice &device,
3795 const Utf8Str &newlyUuid)
3796{
3797 HRESULT rc = S_OK;
3798
3799 /* save for restoring */
3800 mapNewUUIDsToOriginalUUIDs.insert(std::make_pair(newlyUuid, device.uuid.toString()));
3801
3802 return rc;
3803}
3804
3805HRESULT Appliance::ImportStack::restoreOriginalUUIDOfAttachedDevice(settings::MachineConfigFile *config)
3806{
3807 HRESULT rc = S_OK;
3808
3809 settings::StorageControllersList &llControllers = config->storageMachine.llStorageControllers;
3810 settings::StorageControllersList::iterator itscl;
3811 for (itscl = llControllers.begin();
3812 itscl != llControllers.end();
3813 ++itscl)
3814 {
3815 settings::AttachedDevicesList &llAttachments = itscl->llAttachedDevices;
3816 settings::AttachedDevicesList::iterator itadl = llAttachments.begin();
3817 while (itadl != llAttachments.end())
3818 {
3819 std::map<Utf8Str , Utf8Str>::iterator it =
3820 mapNewUUIDsToOriginalUUIDs.find(itadl->uuid.toString());
3821 if(it!=mapNewUUIDsToOriginalUUIDs.end())
3822 {
3823 Utf8Str uuidOriginal = it->second;
3824 itadl->uuid = Guid(uuidOriginal);
3825 mapNewUUIDsToOriginalUUIDs.erase(it->first);
3826 }
3827 ++itadl;
3828 }
3829 }
3830
3831 return rc;
3832}
3833
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