VirtualBox

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

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

Main: Removed the VBOX_WITH_S3 code because we haven't maintained it properly for years.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 159.9 KB
Line 
1/* $Id: ApplianceImplImport.cpp 59577 2016-02-04 14:18:36Z 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));
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 = NULL;
2138
2139 if ((pszSuff = RTPathSuffix(strTargetPath->c_str()))!=NULL)
2140 {
2141 /*
2142 * Figure out which format the user like to have. Default is VMDK
2143 * or it can be VDI if according command-line option is set
2144 */
2145
2146 /*
2147 * We need a proper target format
2148 * if target format has been changed by user via GUI import wizard
2149 * or via VBoxManage import command (option --importtovdi)
2150 * then we need properly process such format like ISO
2151 * Because there is no conversion ISO to VDI
2152 */
2153
2154 pszSuff++;
2155 trgFormat = pSysProps->i_mediumFormatFromExtension(pszSuff);
2156 if (trgFormat.isNull())
2157 {
2158 rc = setError(E_FAIL,
2159 tr("Internal inconsistency looking up medium format for the disk image '%s'"),
2160 di.strHref.c_str());
2161 }
2162
2163 rc = trgFormat->COMGETTER(Name)(bstrFormatName.asOutParam());
2164 if (FAILED(rc)) throw rc;
2165
2166 strTrgFormat = Utf8Str(bstrFormatName);
2167
2168 if(chExt && strTrgFormat.compare("RAW", Utf8Str::CaseInsensitive) != 0)
2169 {
2170 /* change the target extension */
2171 strTrgFormat = "vdi";
2172 trgFormat = pSysProps->i_mediumFormatFromExtension(strTrgFormat);
2173 *strTargetPath = strTargetPath->stripSuffix();
2174 *strTargetPath = strTargetPath->append(".");
2175 *strTargetPath = strTargetPath->append(strTrgFormat.c_str());
2176 }
2177
2178 /* Check the capabilities. We need create capabilities. */
2179 lCabs = 0;
2180 com::SafeArray <MediumFormatCapabilities_T> mediumFormatCap;
2181 rc = trgFormat->COMGETTER(Capabilities)(ComSafeArrayAsOutParam(mediumFormatCap));
2182
2183 if (FAILED(rc))
2184 throw rc;
2185 else
2186 {
2187 for (ULONG j = 0; j < mediumFormatCap.size(); j++)
2188 lCabs |= mediumFormatCap[j];
2189 }
2190
2191 if (!( ((lCabs & MediumFormatCapabilities_CreateFixed) == MediumFormatCapabilities_CreateFixed)
2192 || ((lCabs & MediumFormatCapabilities_CreateDynamic) == MediumFormatCapabilities_CreateDynamic)))
2193 throw setError(VBOX_E_NOT_SUPPORTED,
2194 tr("Could not find a valid medium format for the target disk '%s'"),
2195 strTargetPath->c_str());
2196 }
2197 else
2198 {
2199 throw setError(VBOX_E_FILE_ERROR,
2200 tr("The target disk '%s' has no extension "),
2201 strTargetPath->c_str(), VERR_INVALID_NAME);
2202 }
2203
2204 /* Create an IMedium object. */
2205 pTargetHD.createObject();
2206
2207 /*CD/DVD case*/
2208 if (strTrgFormat.compare("RAW", Utf8Str::CaseInsensitive) == 0)
2209 {
2210 try
2211 {
2212 if (fGzipUsed == true)
2213 {
2214 /*
2215 * The source and target pathes are the same.
2216 * It means that we have the needed file already.
2217 * For example, in GZIP case, we decompress the file and save it in the target path,
2218 * but with some prefix like "temp_". See part "check read file to GZIP compression" earlier
2219 * in this function.
2220 * Just rename the file by deleting "temp_" from it's name
2221 */
2222 vrc = RTFileRename(strSrcFilePath.c_str(), strTargetPath->c_str(), RTPATHRENAME_FLAGS_NO_REPLACE);
2223 if (RT_FAILURE(vrc))
2224 throw setError(VBOX_E_FILE_ERROR,
2225 tr("Could not rename the file '%s' (%Rrc)"),
2226 RTPathFilename(strSourceOVF.c_str()), vrc);
2227 }
2228 else
2229 {
2230 /* Calculating SHA digest for ISO file while copying one */
2231 vrc = copyFileAndCalcShaDigest(strSrcFilePath.c_str(),
2232 strTargetPath->c_str(),
2233 pCallbacks,
2234 pRealUsedStorage);
2235
2236 if (RT_FAILURE(vrc))
2237 throw setError(VBOX_E_FILE_ERROR,
2238 tr("Could not copy ISO file '%s' listed in the OVF file (%Rrc)"),
2239 RTPathFilename(strSourceOVF.c_str()), vrc);
2240 }
2241 }
2242 catch (HRESULT /*arc*/)
2243 {
2244 throw;
2245 }
2246
2247 /* Advance to the next operation. */
2248 /* operation's weight, as set up with the IProgress originally */
2249 stack.pProgress->SetNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"),
2250 RTPathFilename(strSourceOVF.c_str())).raw(),
2251 di.ulSuggestedSizeMB);
2252 }
2253 else/* HDD case*/
2254 {
2255 rc = pTargetHD->init(mVirtualBox,
2256 strTrgFormat,
2257 *strTargetPath,
2258 Guid::Empty /* media registry: none yet */,
2259 DeviceType_HardDisk);
2260 if (FAILED(rc)) throw rc;
2261
2262 /* Now create an empty hard disk. */
2263 rc = mVirtualBox->CreateMedium(Bstr(strTrgFormat).raw(),
2264 Bstr(*strTargetPath).raw(),
2265 AccessMode_ReadWrite, DeviceType_HardDisk,
2266 ComPtr<IMedium>(pTargetHD).asOutParam());
2267 if (FAILED(rc)) throw rc;
2268
2269 /* If strHref is empty we have to create a new file. */
2270 if (strSourceOVF.isEmpty())
2271 {
2272 com::SafeArray<MediumVariant_T> mediumVariant;
2273 mediumVariant.push_back(MediumVariant_Standard);
2274 /* Create a dynamic growing disk image with the given capacity. */
2275 rc = pTargetHD->CreateBaseStorage(di.iCapacity / _1M,
2276 ComSafeArrayAsInParam(mediumVariant),
2277 ComPtr<IProgress>(pProgress).asOutParam());
2278 if (FAILED(rc)) throw rc;
2279
2280 /* Advance to the next operation. */
2281 /* operation's weight, as set up with the IProgress originally */
2282 stack.pProgress->SetNextOperation(BstrFmt(tr("Creating disk image '%s'"),
2283 strTargetPath->c_str()).raw(),
2284 di.ulSuggestedSizeMB);
2285 }
2286 else
2287 {
2288 /* We need a proper source format description */
2289 /* Which format to use? */
2290 ComObjPtr<MediumFormat> srcFormat;
2291 rc = i_findMediumFormatFromDiskImage(di, srcFormat);
2292 if (FAILED(rc))
2293 throw setError(VBOX_E_NOT_SUPPORTED,
2294 tr("Could not find a valid medium format for the source disk '%s' "
2295 "Check correctness of the image format URL in the OVF description file "
2296 "or extension of the image"),
2297 RTPathFilename(strSourceOVF.c_str()));
2298
2299 /* Clone the source disk image */
2300 ComObjPtr<Medium> nullParent;
2301 rc = pTargetHD->i_importFile(strSrcFilePath.c_str(),
2302 srcFormat,
2303 MediumVariant_Standard,
2304 pCallbacks, pRealUsedStorage,
2305 nullParent,
2306 pProgress);
2307 if (FAILED(rc)) throw rc;
2308
2309
2310
2311 /* Advance to the next operation. */
2312 /* operation's weight, as set up with the IProgress originally */
2313 stack.pProgress->SetNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"),
2314 RTPathFilename(strSourceOVF.c_str())).raw(),
2315 di.ulSuggestedSizeMB);
2316 }
2317
2318 /* Now wait for the background disk operation to complete; this throws
2319 * HRESULTs on error. */
2320 ComPtr<IProgress> pp(pProgress);
2321 i_waitForAsyncProgress(stack.pProgress, pp);
2322
2323 if (fGzipUsed == true)
2324 {
2325 /*
2326 * Just delete the temporary file
2327 */
2328 vrc = RTFileDelete(strSrcFilePath.c_str());
2329 if (RT_FAILURE(vrc))
2330 setWarning(VBOX_E_FILE_ERROR,
2331 tr("Could not delete the file '%s' (%Rrc)"),
2332 RTPathFilename(strSrcFilePath.c_str()), vrc);
2333 }
2334 }
2335 }
2336 catch (...)
2337 {
2338 if (pFileIo)
2339 RTMemFree(pFileIo);
2340
2341 throw;
2342 }
2343 }
2344
2345 if (pFileIo)
2346 RTMemFree(pFileIo);
2347
2348 /* Add the newly create disk path + a corresponding digest the our list for
2349 * later manifest verification. */
2350 if (pStorage) /** @todo figure out when this undocumented parameter could be NULL and what implications it has. */
2351 {
2352 vrc = RTManifestEntrySetAttr(stack.hSrcDisksManifest,
2353 strSourceOVF.c_str(),
2354 NULL /*pszAttr*/,
2355 pStorage->strDigest.c_str(),
2356 pStorage->fSha256 ? RTMANIFEST_ATTR_SHA256 : RTMANIFEST_ATTR_SHA1);
2357 if (RT_FAILURE(vrc))
2358 throw setError(VBOX_E_IPRT_ERROR, "RTManifestSetAttr failed on '%s' = '%s' (%Rrc)",
2359 strSourceOVF.c_str(), pStorage->strDigest.c_str(), vrc);
2360 }
2361}
2362
2363/**
2364 * Imports one OVF virtual system (described by the given ovf::VirtualSystem and VirtualSystemDescription)
2365 * into VirtualBox by creating an IMachine instance, which is returned.
2366 *
2367 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
2368 * up any leftovers from this function. For this, the given ImportStack instance has received information
2369 * about what needs cleaning up (to support rollback).
2370 *
2371 * @param vsysThis OVF virtual system (machine) to import.
2372 * @param vsdescThis Matching virtual system description (machine) to import.
2373 * @param pNewMachine out: Newly created machine.
2374 * @param stack Cleanup stack for when this throws.
2375 */
2376void Appliance::i_importMachineGeneric(const ovf::VirtualSystem &vsysThis,
2377 ComObjPtr<VirtualSystemDescription> &vsdescThis,
2378 ComPtr<IMachine> &pNewMachine,
2379 ImportStack &stack,
2380 PVDINTERFACEIO pCallbacks,
2381 PSHASTORAGE pStorage)
2382{
2383 LogFlowFuncEnter();
2384 HRESULT rc;
2385
2386 // Get the instance of IGuestOSType which matches our string guest OS type so we
2387 // can use recommended defaults for the new machine where OVF doesn't provide any
2388 ComPtr<IGuestOSType> osType;
2389 rc = mVirtualBox->GetGuestOSType(Bstr(stack.strOsTypeVBox).raw(), osType.asOutParam());
2390 if (FAILED(rc)) throw rc;
2391
2392 /* Create the machine */
2393 SafeArray<BSTR> groups; /* no groups */
2394 rc = mVirtualBox->CreateMachine(NULL, /* machine name: use default */
2395 Bstr(stack.strNameVBox).raw(),
2396 ComSafeArrayAsInParam(groups),
2397 Bstr(stack.strOsTypeVBox).raw(),
2398 NULL, /* aCreateFlags */
2399 pNewMachine.asOutParam());
2400 if (FAILED(rc)) throw rc;
2401
2402 // set the description
2403 if (!stack.strDescription.isEmpty())
2404 {
2405 rc = pNewMachine->COMSETTER(Description)(Bstr(stack.strDescription).raw());
2406 if (FAILED(rc)) throw rc;
2407 }
2408
2409 // CPU count
2410 rc = pNewMachine->COMSETTER(CPUCount)(stack.cCPUs);
2411 if (FAILED(rc)) throw rc;
2412
2413 if (stack.fForceHWVirt)
2414 {
2415 rc = pNewMachine->SetHWVirtExProperty(HWVirtExPropertyType_Enabled, TRUE);
2416 if (FAILED(rc)) throw rc;
2417 }
2418
2419 // RAM
2420 rc = pNewMachine->COMSETTER(MemorySize)(stack.ulMemorySizeMB);
2421 if (FAILED(rc)) throw rc;
2422
2423 /* VRAM */
2424 /* Get the recommended VRAM for this guest OS type */
2425 ULONG vramVBox;
2426 rc = osType->COMGETTER(RecommendedVRAM)(&vramVBox);
2427 if (FAILED(rc)) throw rc;
2428
2429 /* Set the VRAM */
2430 rc = pNewMachine->COMSETTER(VRAMSize)(vramVBox);
2431 if (FAILED(rc)) throw rc;
2432
2433 // I/O APIC: Generic OVF has no setting for this. Enable it if we
2434 // import a Windows VM because if if Windows was installed without IOAPIC,
2435 // it will not mind finding an one later on, but if Windows was installed
2436 // _with_ an IOAPIC, it will bluescreen if it's not found
2437 if (!stack.fForceIOAPIC)
2438 {
2439 Bstr bstrFamilyId;
2440 rc = osType->COMGETTER(FamilyId)(bstrFamilyId.asOutParam());
2441 if (FAILED(rc)) throw rc;
2442 if (bstrFamilyId == "Windows")
2443 stack.fForceIOAPIC = true;
2444 }
2445
2446 if (stack.fForceIOAPIC)
2447 {
2448 ComPtr<IBIOSSettings> pBIOSSettings;
2449 rc = pNewMachine->COMGETTER(BIOSSettings)(pBIOSSettings.asOutParam());
2450 if (FAILED(rc)) throw rc;
2451
2452 rc = pBIOSSettings->COMSETTER(IOAPICEnabled)(TRUE);
2453 if (FAILED(rc)) throw rc;
2454 }
2455
2456 if (!stack.strAudioAdapter.isEmpty())
2457 if (stack.strAudioAdapter.compare("null", Utf8Str::CaseInsensitive) != 0)
2458 {
2459 uint32_t audio = RTStrToUInt32(stack.strAudioAdapter.c_str()); // should be 0 for AC97
2460 ComPtr<IAudioAdapter> audioAdapter;
2461 rc = pNewMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam());
2462 if (FAILED(rc)) throw rc;
2463 rc = audioAdapter->COMSETTER(Enabled)(true);
2464 if (FAILED(rc)) throw rc;
2465 rc = audioAdapter->COMSETTER(AudioController)(static_cast<AudioControllerType_T>(audio));
2466 if (FAILED(rc)) throw rc;
2467 }
2468
2469#ifdef VBOX_WITH_USB
2470 /* USB Controller */
2471 if (stack.fUSBEnabled)
2472 {
2473 ComPtr<IUSBController> usbController;
2474 rc = pNewMachine->AddUSBController(Bstr("OHCI").raw(), USBControllerType_OHCI, usbController.asOutParam());
2475 if (FAILED(rc)) throw rc;
2476 }
2477#endif /* VBOX_WITH_USB */
2478
2479 /* Change the network adapters */
2480 uint32_t maxNetworkAdapters = Global::getMaxNetworkAdapters(ChipsetType_PIIX3);
2481
2482 std::list<VirtualSystemDescriptionEntry*> vsdeNW = vsdescThis->i_findByType(VirtualSystemDescriptionType_NetworkAdapter);
2483 if (vsdeNW.empty())
2484 {
2485 /* No network adapters, so we have to disable our default one */
2486 ComPtr<INetworkAdapter> nwVBox;
2487 rc = pNewMachine->GetNetworkAdapter(0, nwVBox.asOutParam());
2488 if (FAILED(rc)) throw rc;
2489 rc = nwVBox->COMSETTER(Enabled)(false);
2490 if (FAILED(rc)) throw rc;
2491 }
2492 else if (vsdeNW.size() > maxNetworkAdapters)
2493 throw setError(VBOX_E_FILE_ERROR,
2494 tr("Too many network adapters: OVF requests %d network adapters, "
2495 "but VirtualBox only supports %d"),
2496 vsdeNW.size(), maxNetworkAdapters);
2497 else
2498 {
2499 list<VirtualSystemDescriptionEntry*>::const_iterator nwIt;
2500 size_t a = 0;
2501 for (nwIt = vsdeNW.begin();
2502 nwIt != vsdeNW.end();
2503 ++nwIt, ++a)
2504 {
2505 const VirtualSystemDescriptionEntry* pvsys = *nwIt;
2506
2507 const Utf8Str &nwTypeVBox = pvsys->strVBoxCurrent;
2508 uint32_t tt1 = RTStrToUInt32(nwTypeVBox.c_str());
2509 ComPtr<INetworkAdapter> pNetworkAdapter;
2510 rc = pNewMachine->GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
2511 if (FAILED(rc)) throw rc;
2512 /* Enable the network card & set the adapter type */
2513 rc = pNetworkAdapter->COMSETTER(Enabled)(true);
2514 if (FAILED(rc)) throw rc;
2515 rc = pNetworkAdapter->COMSETTER(AdapterType)(static_cast<NetworkAdapterType_T>(tt1));
2516 if (FAILED(rc)) throw rc;
2517
2518 // default is NAT; change to "bridged" if extra conf says so
2519 if (pvsys->strExtraConfigCurrent.endsWith("type=Bridged", Utf8Str::CaseInsensitive))
2520 {
2521 /* Attach to the right interface */
2522 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_Bridged);
2523 if (FAILED(rc)) throw rc;
2524 ComPtr<IHost> host;
2525 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
2526 if (FAILED(rc)) throw rc;
2527 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
2528 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
2529 if (FAILED(rc)) throw rc;
2530 // We search for the first host network interface which
2531 // is usable for bridged networking
2532 for (size_t j = 0;
2533 j < nwInterfaces.size();
2534 ++j)
2535 {
2536 HostNetworkInterfaceType_T itype;
2537 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
2538 if (FAILED(rc)) throw rc;
2539 if (itype == HostNetworkInterfaceType_Bridged)
2540 {
2541 Bstr name;
2542 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
2543 if (FAILED(rc)) throw rc;
2544 /* Set the interface name to attach to */
2545 rc = pNetworkAdapter->COMSETTER(BridgedInterface)(name.raw());
2546 if (FAILED(rc)) throw rc;
2547 break;
2548 }
2549 }
2550 }
2551 /* Next test for host only interfaces */
2552 else if (pvsys->strExtraConfigCurrent.endsWith("type=HostOnly", Utf8Str::CaseInsensitive))
2553 {
2554 /* Attach to the right interface */
2555 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_HostOnly);
2556 if (FAILED(rc)) throw rc;
2557 ComPtr<IHost> host;
2558 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
2559 if (FAILED(rc)) throw rc;
2560 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
2561 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
2562 if (FAILED(rc)) throw rc;
2563 // We search for the first host network interface which
2564 // is usable for host only networking
2565 for (size_t j = 0;
2566 j < nwInterfaces.size();
2567 ++j)
2568 {
2569 HostNetworkInterfaceType_T itype;
2570 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
2571 if (FAILED(rc)) throw rc;
2572 if (itype == HostNetworkInterfaceType_HostOnly)
2573 {
2574 Bstr name;
2575 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
2576 if (FAILED(rc)) throw rc;
2577 /* Set the interface name to attach to */
2578 rc = pNetworkAdapter->COMSETTER(HostOnlyInterface)(name.raw());
2579 if (FAILED(rc)) throw rc;
2580 break;
2581 }
2582 }
2583 }
2584 /* Next test for internal interfaces */
2585 else if (pvsys->strExtraConfigCurrent.endsWith("type=Internal", Utf8Str::CaseInsensitive))
2586 {
2587 /* Attach to the right interface */
2588 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_Internal);
2589 if (FAILED(rc)) throw rc;
2590 }
2591 /* Next test for Generic interfaces */
2592 else if (pvsys->strExtraConfigCurrent.endsWith("type=Generic", Utf8Str::CaseInsensitive))
2593 {
2594 /* Attach to the right interface */
2595 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_Generic);
2596 if (FAILED(rc)) throw rc;
2597 }
2598
2599 /* Next test for NAT network interfaces */
2600 else if (pvsys->strExtraConfigCurrent.endsWith("type=NATNetwork", Utf8Str::CaseInsensitive))
2601 {
2602 /* Attach to the right interface */
2603 rc = pNetworkAdapter->COMSETTER(AttachmentType)(NetworkAttachmentType_NATNetwork);
2604 if (FAILED(rc)) throw rc;
2605 com::SafeIfaceArray<INATNetwork> nwNATNetworks;
2606 rc = mVirtualBox->COMGETTER(NATNetworks)(ComSafeArrayAsOutParam(nwNATNetworks));
2607 if (FAILED(rc)) throw rc;
2608 // Pick the first NAT network (if there is any)
2609 if (nwNATNetworks.size())
2610 {
2611 Bstr name;
2612 rc = nwNATNetworks[0]->COMGETTER(NetworkName)(name.asOutParam());
2613 if (FAILED(rc)) throw rc;
2614 /* Set the NAT network name to attach to */
2615 rc = pNetworkAdapter->COMSETTER(NATNetwork)(name.raw());
2616 if (FAILED(rc)) throw rc;
2617 break;
2618 }
2619 }
2620 }
2621 }
2622
2623 // IDE Hard disk controller
2624 std::list<VirtualSystemDescriptionEntry*> vsdeHDCIDE =
2625 vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskControllerIDE);
2626 /*
2627 * In OVF (at least VMware's version of it), an IDE controller has two ports,
2628 * so VirtualBox's single IDE controller with two channels and two ports each counts as
2629 * two OVF IDE controllers -- so we accept one or two such IDE controllers
2630 */
2631 size_t cIDEControllers = vsdeHDCIDE.size();
2632 if (cIDEControllers > 2)
2633 throw setError(VBOX_E_FILE_ERROR,
2634 tr("Too many IDE controllers in OVF; import facility only supports two"));
2635 if (!vsdeHDCIDE.empty())
2636 {
2637 // one or two IDE controllers present in OVF: add one VirtualBox controller
2638 ComPtr<IStorageController> pController;
2639 rc = pNewMachine->AddStorageController(Bstr("IDE Controller").raw(), StorageBus_IDE, pController.asOutParam());
2640 if (FAILED(rc)) throw rc;
2641
2642 const char *pcszIDEType = vsdeHDCIDE.front()->strVBoxCurrent.c_str();
2643 if (!strcmp(pcszIDEType, "PIIX3"))
2644 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX3);
2645 else if (!strcmp(pcszIDEType, "PIIX4"))
2646 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX4);
2647 else if (!strcmp(pcszIDEType, "ICH6"))
2648 rc = pController->COMSETTER(ControllerType)(StorageControllerType_ICH6);
2649 else
2650 throw setError(VBOX_E_FILE_ERROR,
2651 tr("Invalid IDE controller type \"%s\""),
2652 pcszIDEType);
2653 if (FAILED(rc)) throw rc;
2654 }
2655
2656 /* Hard disk controller SATA */
2657 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSATA =
2658 vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskControllerSATA);
2659 if (vsdeHDCSATA.size() > 1)
2660 throw setError(VBOX_E_FILE_ERROR,
2661 tr("Too many SATA controllers in OVF; import facility only supports one"));
2662 if (!vsdeHDCSATA.empty())
2663 {
2664 ComPtr<IStorageController> pController;
2665 const Utf8Str &hdcVBox = vsdeHDCSATA.front()->strVBoxCurrent;
2666 if (hdcVBox == "AHCI")
2667 {
2668 rc = pNewMachine->AddStorageController(Bstr("SATA Controller").raw(),
2669 StorageBus_SATA,
2670 pController.asOutParam());
2671 if (FAILED(rc)) throw rc;
2672 }
2673 else
2674 throw setError(VBOX_E_FILE_ERROR,
2675 tr("Invalid SATA controller type \"%s\""),
2676 hdcVBox.c_str());
2677 }
2678
2679 /* Hard disk controller SCSI */
2680 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSCSI =
2681 vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskControllerSCSI);
2682 if (vsdeHDCSCSI.size() > 1)
2683 throw setError(VBOX_E_FILE_ERROR,
2684 tr("Too many SCSI controllers in OVF; import facility only supports one"));
2685 if (!vsdeHDCSCSI.empty())
2686 {
2687 ComPtr<IStorageController> pController;
2688 Bstr bstrName(L"SCSI Controller");
2689 StorageBus_T busType = StorageBus_SCSI;
2690 StorageControllerType_T controllerType;
2691 const Utf8Str &hdcVBox = vsdeHDCSCSI.front()->strVBoxCurrent;
2692 if (hdcVBox == "LsiLogic")
2693 controllerType = StorageControllerType_LsiLogic;
2694 else if (hdcVBox == "LsiLogicSas")
2695 {
2696 // OVF treats LsiLogicSas as a SCSI controller but VBox considers it a class of its own
2697 bstrName = L"SAS Controller";
2698 busType = StorageBus_SAS;
2699 controllerType = StorageControllerType_LsiLogicSas;
2700 }
2701 else if (hdcVBox == "BusLogic")
2702 controllerType = StorageControllerType_BusLogic;
2703 else
2704 throw setError(VBOX_E_FILE_ERROR,
2705 tr("Invalid SCSI controller type \"%s\""),
2706 hdcVBox.c_str());
2707
2708 rc = pNewMachine->AddStorageController(bstrName.raw(), busType, pController.asOutParam());
2709 if (FAILED(rc)) throw rc;
2710 rc = pController->COMSETTER(ControllerType)(controllerType);
2711 if (FAILED(rc)) throw rc;
2712 }
2713
2714 /* Hard disk controller SAS */
2715 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSAS =
2716 vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskControllerSAS);
2717 if (vsdeHDCSAS.size() > 1)
2718 throw setError(VBOX_E_FILE_ERROR,
2719 tr("Too many SAS controllers in OVF; import facility only supports one"));
2720 if (!vsdeHDCSAS.empty())
2721 {
2722 ComPtr<IStorageController> pController;
2723 rc = pNewMachine->AddStorageController(Bstr(L"SAS Controller").raw(),
2724 StorageBus_SAS,
2725 pController.asOutParam());
2726 if (FAILED(rc)) throw rc;
2727 rc = pController->COMSETTER(ControllerType)(StorageControllerType_LsiLogicSas);
2728 if (FAILED(rc)) throw rc;
2729 }
2730
2731 /* Now its time to register the machine before we add any hard disks */
2732 rc = mVirtualBox->RegisterMachine(pNewMachine);
2733 if (FAILED(rc)) throw rc;
2734
2735 // store new machine for roll-back in case of errors
2736 Bstr bstrNewMachineId;
2737 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
2738 if (FAILED(rc)) throw rc;
2739 Guid uuidNewMachine(bstrNewMachineId);
2740 m->llGuidsMachinesCreated.push_back(uuidNewMachine);
2741
2742 // Add floppies and CD-ROMs to the appropriate controllers.
2743 std::list<VirtualSystemDescriptionEntry*> vsdeFloppy = vsdescThis->i_findByType(VirtualSystemDescriptionType_Floppy);
2744 if (vsdeFloppy.size() > 1)
2745 throw setError(VBOX_E_FILE_ERROR,
2746 tr("Too many floppy controllers in OVF; import facility only supports one"));
2747 std::list<VirtualSystemDescriptionEntry*> vsdeCDROM = vsdescThis->i_findByType(VirtualSystemDescriptionType_CDROM);
2748 if ( !vsdeFloppy.empty()
2749 || !vsdeCDROM.empty()
2750 )
2751 {
2752 // If there's an error here we need to close the session, so
2753 // we need another try/catch block.
2754
2755 try
2756 {
2757 // to attach things we need to open a session for the new machine
2758 rc = pNewMachine->LockMachine(stack.pSession, LockType_Write);
2759 if (FAILED(rc)) throw rc;
2760 stack.fSessionOpen = true;
2761
2762 ComPtr<IMachine> sMachine;
2763 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
2764 if (FAILED(rc)) throw rc;
2765
2766 // floppy first
2767 if (vsdeFloppy.size() == 1)
2768 {
2769 ComPtr<IStorageController> pController;
2770 rc = sMachine->AddStorageController(Bstr("Floppy Controller").raw(),
2771 StorageBus_Floppy,
2772 pController.asOutParam());
2773 if (FAILED(rc)) throw rc;
2774
2775 Bstr bstrName;
2776 rc = pController->COMGETTER(Name)(bstrName.asOutParam());
2777 if (FAILED(rc)) throw rc;
2778
2779 // this is for rollback later
2780 MyHardDiskAttachment mhda;
2781 mhda.pMachine = pNewMachine;
2782 mhda.controllerType = bstrName;
2783 mhda.lControllerPort = 0;
2784 mhda.lDevice = 0;
2785
2786 Log(("Attaching floppy\n"));
2787
2788 rc = sMachine->AttachDevice(mhda.controllerType.raw(),
2789 mhda.lControllerPort,
2790 mhda.lDevice,
2791 DeviceType_Floppy,
2792 NULL);
2793 if (FAILED(rc)) throw rc;
2794
2795 stack.llHardDiskAttachments.push_back(mhda);
2796 }
2797
2798 rc = sMachine->SaveSettings();
2799 if (FAILED(rc)) throw rc;
2800
2801 // only now that we're done with all disks, close the session
2802 rc = stack.pSession->UnlockMachine();
2803 if (FAILED(rc)) throw rc;
2804 stack.fSessionOpen = false;
2805 }
2806 catch(HRESULT aRC)
2807 {
2808 com::ErrorInfo info;
2809
2810 if (stack.fSessionOpen)
2811 stack.pSession->UnlockMachine();
2812
2813 if (info.isFullAvailable())
2814 throw setError(aRC, Utf8Str(info.getText()).c_str());
2815 else
2816 throw setError(aRC, "Unknown error during OVF import");
2817 }
2818 }
2819
2820 // create the hard disks & connect them to the appropriate controllers
2821 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskImage);
2822 if (!avsdeHDs.empty())
2823 {
2824 // If there's an error here we need to close the session, so
2825 // we need another try/catch block.
2826 try
2827 {
2828#ifdef LOG_ENABLED
2829 if (LogIsEnabled())
2830 {
2831 size_t i = 0;
2832 for (list<VirtualSystemDescriptionEntry*>::const_iterator itHD = avsdeHDs.begin();
2833 itHD != avsdeHDs.end(); ++itHD, i++)
2834 Log(("avsdeHDs[%zu]: strRef=%s strOvf=%s\n", i, (*itHD)->strRef.c_str(), (*itHD)->strOvf.c_str()));
2835 i = 0;
2836 for (ovf::DiskImagesMap::const_iterator itDisk = stack.mapDisks.begin(); itDisk != stack.mapDisks.end(); ++itDisk)
2837 Log(("mapDisks[%zu]: strDiskId=%s strHref=%s\n",
2838 i, itDisk->second.strDiskId.c_str(), itDisk->second.strHref.c_str()));
2839
2840 }
2841#endif
2842
2843 // to attach things we need to open a session for the new machine
2844 rc = pNewMachine->LockMachine(stack.pSession, LockType_Write);
2845 if (FAILED(rc)) throw rc;
2846 stack.fSessionOpen = true;
2847
2848 /* get VM name from virtual system description. Only one record is possible (size of list is equal 1). */
2849 std::list<VirtualSystemDescriptionEntry*> vmName = vsdescThis->i_findByType(VirtualSystemDescriptionType_Name);
2850 std::list<VirtualSystemDescriptionEntry*>::iterator vmNameIt = vmName.begin();
2851 VirtualSystemDescriptionEntry* vmNameEntry = *vmNameIt;
2852
2853
2854 ovf::DiskImagesMap::const_iterator oit = stack.mapDisks.begin();
2855 std::set<RTCString> disksResolvedNames;
2856
2857 uint32_t cImportedDisks = 0;
2858
2859 while (oit != stack.mapDisks.end() && cImportedDisks != avsdeHDs.size())
2860 {
2861 ovf::DiskImage diCurrent = oit->second;
2862 ovf::VirtualDisksMap::const_iterator itVDisk = vsysThis.mapVirtualDisks.begin();
2863
2864 VirtualSystemDescriptionEntry *vsdeTargetHD = 0;
2865 Log(("diCurrent.strDiskId=%s diCurrent.strHref=%s\n", diCurrent.strDiskId.c_str(), diCurrent.strHref.c_str()));
2866
2867 /*
2868 *
2869 * Iterate over all given disk images of the virtual system
2870 * disks description. We need to find the target disk path,
2871 * which could be changed by the user.
2872 *
2873 */
2874 {
2875 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
2876 for (itHD = avsdeHDs.begin();
2877 itHD != avsdeHDs.end();
2878 ++itHD)
2879 {
2880 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
2881 if (vsdeHD->strRef == diCurrent.strDiskId)
2882 {
2883 vsdeTargetHD = vsdeHD;
2884 break;
2885 }
2886 }
2887 if (!vsdeTargetHD)
2888 {
2889 /* possible case if a disk image belongs to other virtual system (OVF package with multiple VMs inside) */
2890 Log1Warning(("OVA/OVF import: Disk image %s was missed during import of VM %s\n",
2891 oit->first.c_str(), vmNameEntry->strOvf.c_str()));
2892 NOREF(vmNameEntry);
2893 ++oit;
2894 continue;
2895 }
2896
2897 //diCurrent.strDiskId contains the disk identifier (e.g. "vmdisk1"), which should exist
2898 //in the virtual system's disks map under that ID and also in the global images map
2899 itVDisk = vsysThis.mapVirtualDisks.find(diCurrent.strDiskId);
2900 if (itVDisk == vsysThis.mapVirtualDisks.end())
2901 throw setError(E_FAIL,
2902 tr("Internal inconsistency looking up disk image '%s'"),
2903 diCurrent.strHref.c_str());
2904 }
2905
2906 /*
2907 * preliminary check availability of the image
2908 * This step is useful if image is placed in the OVA (TAR) package
2909 */
2910
2911 Utf8Str name = i_applianceIOName(applianceIOTar);
2912
2913 if (strncmp(pStorage->pVDImageIfaces->pszInterfaceName, name.c_str(), name.length()) == 0)
2914 {
2915 /* It means that we possibly have imported the storage earlier on the previous loop steps*/
2916 std::set<RTCString>::const_iterator h = disksResolvedNames.find(diCurrent.strHref);
2917 if (h != disksResolvedNames.end())
2918 {
2919 /* Yes, disk name was found, we can skip it*/
2920 ++oit;
2921 continue;
2922 }
2923
2924 RTCString availableImage(diCurrent.strHref);
2925
2926 rc = i_preCheckImageAvailability(pStorage, availableImage);
2927
2928 if (SUCCEEDED(rc))
2929 {
2930 /* current opened file isn't the same as passed one */
2931 if (availableImage.compare(diCurrent.strHref, Utf8Str::CaseInsensitive) != 0)
2932 {
2933 /*
2934 * availableImage contains the disk file reference (e.g. "disk1.vmdk"), which should exist
2935 * in the global images map.
2936 * And find the disk from the OVF's disk list
2937 *
2938 */
2939 {
2940 ovf::DiskImagesMap::const_iterator itDiskImage = stack.mapDisks.begin();
2941 while (++itDiskImage != stack.mapDisks.end())
2942 {
2943 if (itDiskImage->second.strHref.compare(availableImage, Utf8Str::CaseInsensitive) == 0)
2944 break;
2945 }
2946 if (itDiskImage == stack.mapDisks.end())
2947 {
2948 throw setError(E_FAIL,
2949 tr("Internal inconsistency looking up disk image '%s'. "
2950 "Check compliance OVA package structure and file names "
2951 "references in the section <References> in the OVF file."),
2952 availableImage.c_str());
2953 }
2954
2955 /* replace with a new found disk image */
2956 diCurrent = *(&itDiskImage->second);
2957 }
2958
2959 /*
2960 * Again iterate over all given disk images of the virtual system
2961 * disks description using the found disk image
2962 */
2963 {
2964 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
2965 for (itHD = avsdeHDs.begin();
2966 itHD != avsdeHDs.end();
2967 ++itHD)
2968 {
2969 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
2970 if (vsdeHD->strRef == diCurrent.strDiskId)
2971 {
2972 vsdeTargetHD = vsdeHD;
2973 break;
2974 }
2975 }
2976 if (!vsdeTargetHD)
2977 {
2978 /*
2979 * in this case it's an error because something wrong with OVF description file.
2980 * May be VBox imports OVA package with wrong file sequence inside the archive.
2981 */
2982 throw setError(E_FAIL,
2983 tr("Internal inconsistency looking up disk image '%s'"),
2984 diCurrent.strHref.c_str());
2985 }
2986
2987 itVDisk = vsysThis.mapVirtualDisks.find(diCurrent.strDiskId);
2988 if (itVDisk == vsysThis.mapVirtualDisks.end())
2989 throw setError(E_FAIL,
2990 tr("Internal inconsistency looking up disk image '%s'"),
2991 diCurrent.strHref.c_str());
2992 }
2993 }
2994 else
2995 {
2996 ++oit;
2997 }
2998 }
2999 else
3000 {
3001 ++oit;
3002 continue;
3003 }
3004 }
3005 else
3006 {
3007 /* just continue with normal files*/
3008 ++oit;
3009 }
3010
3011 const ovf::VirtualDisk &ovfVdisk = itVDisk->second;
3012
3013 /* very important to store disk name for the next checks */
3014 disksResolvedNames.insert(diCurrent.strHref);
3015
3016 ComObjPtr<Medium> pTargetHD;
3017
3018 Utf8Str savedVBoxCurrent = vsdeTargetHD->strVBoxCurrent;
3019
3020 i_importOneDiskImage(diCurrent,
3021 &vsdeTargetHD->strVBoxCurrent,
3022 pTargetHD,
3023 stack,
3024 pCallbacks,
3025 pStorage);
3026
3027 // now use the new uuid to attach the disk image to our new machine
3028 ComPtr<IMachine> sMachine;
3029 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
3030 if (FAILED(rc))
3031 throw rc;
3032
3033 // find the hard disk controller to which we should attach
3034 ovf::HardDiskController hdc = (*vsysThis.mapControllers.find(ovfVdisk.idController)).second;
3035
3036 // this is for rollback later
3037 MyHardDiskAttachment mhda;
3038 mhda.pMachine = pNewMachine;
3039
3040 i_convertDiskAttachmentValues(hdc,
3041 ovfVdisk.ulAddressOnParent,
3042 mhda.controllerType, // Bstr
3043 mhda.lControllerPort,
3044 mhda.lDevice);
3045
3046 Log(("Attaching disk %s to port %d on device %d\n",
3047 vsdeTargetHD->strVBoxCurrent.c_str(), mhda.lControllerPort, mhda.lDevice));
3048
3049 ComObjPtr<MediumFormat> mediumFormat;
3050 rc = i_findMediumFormatFromDiskImage(diCurrent, mediumFormat);
3051 if (FAILED(rc))
3052 throw rc;
3053
3054 Bstr bstrFormatName;
3055 rc = mediumFormat->COMGETTER(Name)(bstrFormatName.asOutParam());
3056 if (FAILED(rc))
3057 throw rc;
3058
3059 Utf8Str vdf = Utf8Str(bstrFormatName);
3060
3061 if (vdf.compare("RAW", Utf8Str::CaseInsensitive) == 0)
3062 {
3063 ComPtr<IMedium> dvdImage(pTargetHD);
3064
3065 rc = mVirtualBox->OpenMedium(Bstr(vsdeTargetHD->strVBoxCurrent).raw(),
3066 DeviceType_DVD,
3067 AccessMode_ReadWrite,
3068 false,
3069 dvdImage.asOutParam());
3070
3071 if (FAILED(rc))
3072 throw rc;
3073
3074 rc = sMachine->AttachDevice(mhda.controllerType.raw(),// wstring name
3075 mhda.lControllerPort, // long controllerPort
3076 mhda.lDevice, // long device
3077 DeviceType_DVD, // DeviceType_T type
3078 dvdImage);
3079 if (FAILED(rc))
3080 throw rc;
3081 }
3082 else
3083 {
3084 rc = sMachine->AttachDevice(mhda.controllerType.raw(),// wstring name
3085 mhda.lControllerPort, // long controllerPort
3086 mhda.lDevice, // long device
3087 DeviceType_HardDisk, // DeviceType_T type
3088 pTargetHD);
3089
3090 if (FAILED(rc))
3091 throw rc;
3092 }
3093
3094 stack.llHardDiskAttachments.push_back(mhda);
3095
3096 rc = sMachine->SaveSettings();
3097 if (FAILED(rc))
3098 throw rc;
3099
3100 /* restore */
3101 vsdeTargetHD->strVBoxCurrent = savedVBoxCurrent;
3102
3103 ++cImportedDisks;
3104
3105 } // end while(oit != stack.mapDisks.end())
3106
3107 /*
3108 * quantity of the imported disks isn't equal to the size of the avsdeHDs list.
3109 */
3110 if(cImportedDisks < avsdeHDs.size())
3111 {
3112 Log1Warning(("Not all disk images were imported for VM %s. Check OVF description file.",
3113 vmNameEntry->strOvf.c_str()));
3114 }
3115
3116 // only now that we're done with all disks, close the session
3117 rc = stack.pSession->UnlockMachine();
3118 if (FAILED(rc))
3119 throw rc;
3120 stack.fSessionOpen = false;
3121 }
3122 catch(HRESULT aRC)
3123 {
3124 com::ErrorInfo info;
3125 if (stack.fSessionOpen)
3126 stack.pSession->UnlockMachine();
3127
3128 if (info.isFullAvailable())
3129 throw setError(aRC, Utf8Str(info.getText()).c_str());
3130 else
3131 throw setError(aRC, "Unknown error during OVF import");
3132 }
3133 }
3134 LogFlowFuncLeave();
3135}
3136
3137/**
3138 * Imports one OVF virtual system (described by a vbox:Machine tag represented by the given config
3139 * structure) into VirtualBox by creating an IMachine instance, which is returned.
3140 *
3141 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
3142 * up any leftovers from this function. For this, the given ImportStack instance has received information
3143 * about what needs cleaning up (to support rollback).
3144 *
3145 * The machine config stored in the settings::MachineConfigFile structure contains the UUIDs of
3146 * the disk attachments used by the machine when it was exported. We also add vbox:uuid attributes
3147 * to the OVF disks sections so we can look them up. While importing these UUIDs into a second host
3148 * will most probably work, reimporting them into the same host will cause conflicts, so we always
3149 * generate new ones on import. This involves the following:
3150 *
3151 * 1) Scan the machine config for disk attachments.
3152 *
3153 * 2) For each disk attachment found, look up the OVF disk image from the disk references section
3154 * and import the disk into VirtualBox, which creates a new UUID for it. In the machine config,
3155 * replace the old UUID with the new one.
3156 *
3157 * 3) Change the machine config according to the OVF virtual system descriptions, in case the
3158 * caller has modified them using setFinalValues().
3159 *
3160 * 4) Create the VirtualBox machine with the modfified machine config.
3161 *
3162 * @param config
3163 * @param pNewMachine
3164 * @param stack
3165 */
3166void Appliance::i_importVBoxMachine(ComObjPtr<VirtualSystemDescription> &vsdescThis,
3167 ComPtr<IMachine> &pReturnNewMachine,
3168 ImportStack &stack,
3169 PVDINTERFACEIO pCallbacks,
3170 PSHASTORAGE pStorage)
3171{
3172 LogFlowFuncEnter();
3173 Assert(vsdescThis->m->pConfig);
3174
3175 HRESULT rc = S_OK;
3176
3177 settings::MachineConfigFile &config = *vsdescThis->m->pConfig;
3178
3179 /*
3180 * step 1): modify machine config according to OVF config, in case the user
3181 * has modified them using setFinalValues()
3182 */
3183
3184 /* OS Type */
3185 config.machineUserData.strOsType = stack.strOsTypeVBox;
3186 /* Description */
3187 config.machineUserData.strDescription = stack.strDescription;
3188 /* CPU count & extented attributes */
3189 config.hardwareMachine.cCPUs = stack.cCPUs;
3190 if (stack.fForceIOAPIC)
3191 config.hardwareMachine.fHardwareVirt = true;
3192 if (stack.fForceIOAPIC)
3193 config.hardwareMachine.biosSettings.fIOAPICEnabled = true;
3194 /* RAM size */
3195 config.hardwareMachine.ulMemorySizeMB = stack.ulMemorySizeMB;
3196
3197/*
3198 <const name="HardDiskControllerIDE" value="14" />
3199 <const name="HardDiskControllerSATA" value="15" />
3200 <const name="HardDiskControllerSCSI" value="16" />
3201 <const name="HardDiskControllerSAS" value="17" />
3202*/
3203
3204#ifdef VBOX_WITH_USB
3205 /* USB controller */
3206 if (stack.fUSBEnabled)
3207 {
3208 /** @todo r=klaus add support for arbitrary USB controller types, this can't handle
3209 * multiple controllers due to its design anyway */
3210 /* usually the OHCI controller is enabled already, need to check */
3211 bool fOHCIEnabled = false;
3212 settings::USBControllerList &llUSBControllers = config.hardwareMachine.usbSettings.llUSBControllers;
3213 settings::USBControllerList::iterator it;
3214 for (it = llUSBControllers.begin(); it != llUSBControllers.end(); ++it)
3215 {
3216 if (it->enmType == USBControllerType_OHCI)
3217 {
3218 fOHCIEnabled = true;
3219 break;
3220 }
3221 }
3222
3223 if (!fOHCIEnabled)
3224 {
3225 settings::USBController ctrl;
3226 ctrl.strName = "OHCI";
3227 ctrl.enmType = USBControllerType_OHCI;
3228
3229 llUSBControllers.push_back(ctrl);
3230 }
3231 }
3232 else
3233 config.hardwareMachine.usbSettings.llUSBControllers.clear();
3234#endif
3235 /* Audio adapter */
3236 if (stack.strAudioAdapter.isNotEmpty())
3237 {
3238 config.hardwareMachine.audioAdapter.fEnabled = true;
3239 config.hardwareMachine.audioAdapter.controllerType = (AudioControllerType_T)stack.strAudioAdapter.toUInt32();
3240 }
3241 else
3242 config.hardwareMachine.audioAdapter.fEnabled = false;
3243 /* Network adapter */
3244 settings::NetworkAdaptersList &llNetworkAdapters = config.hardwareMachine.llNetworkAdapters;
3245 /* First disable all network cards, they will be enabled below again. */
3246 settings::NetworkAdaptersList::iterator it1;
3247 bool fKeepAllMACs = m->optListImport.contains(ImportOptions_KeepAllMACs);
3248 bool fKeepNATMACs = m->optListImport.contains(ImportOptions_KeepNATMACs);
3249 for (it1 = llNetworkAdapters.begin(); it1 != llNetworkAdapters.end(); ++it1)
3250 {
3251 it1->fEnabled = false;
3252 if (!( fKeepAllMACs
3253 || (fKeepNATMACs && it1->mode == NetworkAttachmentType_NAT)
3254 || (fKeepNATMACs && it1->mode == NetworkAttachmentType_NATNetwork)))
3255 Host::i_generateMACAddress(it1->strMACAddress);
3256 }
3257 /* Now iterate over all network entries. */
3258 std::list<VirtualSystemDescriptionEntry*> avsdeNWs = vsdescThis->i_findByType(VirtualSystemDescriptionType_NetworkAdapter);
3259 if (!avsdeNWs.empty())
3260 {
3261 /* Iterate through all network adapter entries and search for the
3262 * corresponding one in the machine config. If one is found, configure
3263 * it based on the user settings. */
3264 list<VirtualSystemDescriptionEntry*>::const_iterator itNW;
3265 for (itNW = avsdeNWs.begin();
3266 itNW != avsdeNWs.end();
3267 ++itNW)
3268 {
3269 VirtualSystemDescriptionEntry *vsdeNW = *itNW;
3270 if ( vsdeNW->strExtraConfigCurrent.startsWith("slot=", Utf8Str::CaseInsensitive)
3271 && vsdeNW->strExtraConfigCurrent.length() > 6)
3272 {
3273 uint32_t iSlot = vsdeNW->strExtraConfigCurrent.substr(5, 1).toUInt32();
3274 /* Iterate through all network adapters in the machine config. */
3275 for (it1 = llNetworkAdapters.begin();
3276 it1 != llNetworkAdapters.end();
3277 ++it1)
3278 {
3279 /* Compare the slots. */
3280 if (it1->ulSlot == iSlot)
3281 {
3282 it1->fEnabled = true;
3283 it1->type = (NetworkAdapterType_T)vsdeNW->strVBoxCurrent.toUInt32();
3284 break;
3285 }
3286 }
3287 }
3288 }
3289 }
3290
3291 /* Floppy controller */
3292 bool fFloppy = vsdescThis->i_findByType(VirtualSystemDescriptionType_Floppy).size() > 0;
3293 /* DVD controller */
3294 bool fDVD = vsdescThis->i_findByType(VirtualSystemDescriptionType_CDROM).size() > 0;
3295 /* Iterate over all storage controller check the attachments and remove
3296 * them when necessary. Also detect broken configs with more than one
3297 * attachment. Old VirtualBox versions (prior to 3.2.10) had all disk
3298 * attachments pointing to the last hard disk image, which causes import
3299 * failures. A long fixed bug, however the OVF files are long lived. */
3300 settings::StorageControllersList &llControllers = config.storageMachine.llStorageControllers;
3301 Guid hdUuid;
3302 uint32_t cDisks = 0;
3303 bool fInconsistent = false;
3304 bool fRepairDuplicate = false;
3305 settings::StorageControllersList::iterator it3;
3306 for (it3 = llControllers.begin();
3307 it3 != llControllers.end();
3308 ++it3)
3309 {
3310 settings::AttachedDevicesList &llAttachments = it3->llAttachedDevices;
3311 settings::AttachedDevicesList::iterator it4 = llAttachments.begin();
3312 while (it4 != llAttachments.end())
3313 {
3314 if ( ( !fDVD
3315 && it4->deviceType == DeviceType_DVD)
3316 ||
3317 ( !fFloppy
3318 && it4->deviceType == DeviceType_Floppy))
3319 {
3320 it4 = llAttachments.erase(it4);
3321 continue;
3322 }
3323 else if (it4->deviceType == DeviceType_HardDisk)
3324 {
3325 const Guid &thisUuid = it4->uuid;
3326 cDisks++;
3327 if (cDisks == 1)
3328 {
3329 if (hdUuid.isZero())
3330 hdUuid = thisUuid;
3331 else
3332 fInconsistent = true;
3333 }
3334 else
3335 {
3336 if (thisUuid.isZero())
3337 fInconsistent = true;
3338 else if (thisUuid == hdUuid)
3339 fRepairDuplicate = true;
3340 }
3341 }
3342 ++it4;
3343 }
3344 }
3345 /* paranoia... */
3346 if (fInconsistent || cDisks == 1)
3347 fRepairDuplicate = false;
3348
3349 /*
3350 * step 2: scan the machine config for media attachments
3351 */
3352 /* get VM name from virtual system description. Only one record is possible (size of list is equal 1). */
3353 std::list<VirtualSystemDescriptionEntry*> vmName = vsdescThis->i_findByType(VirtualSystemDescriptionType_Name);
3354 std::list<VirtualSystemDescriptionEntry*>::iterator vmNameIt = vmName.begin();
3355 VirtualSystemDescriptionEntry* vmNameEntry = *vmNameIt;
3356
3357 /* Get all hard disk descriptions. */
3358 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->i_findByType(VirtualSystemDescriptionType_HardDiskImage);
3359 std::list<VirtualSystemDescriptionEntry*>::iterator avsdeHDsIt = avsdeHDs.begin();
3360 /* paranoia - if there is no 1:1 match do not try to repair. */
3361 if (cDisks != avsdeHDs.size())
3362 fRepairDuplicate = false;
3363
3364 // there must be an image in the OVF disk structs with the same UUID
3365
3366 ovf::DiskImagesMap::const_iterator oit = stack.mapDisks.begin();
3367 std::set<RTCString> disksResolvedNames;
3368
3369 uint32_t cImportedDisks = 0;
3370
3371 while(oit != stack.mapDisks.end() && cImportedDisks != avsdeHDs.size())
3372 {
3373 ovf::DiskImage diCurrent = oit->second;
3374
3375 VirtualSystemDescriptionEntry *vsdeTargetHD = 0;
3376
3377 {
3378 /* Iterate over all given disk images of the virtual system
3379 * disks description. We need to find the target disk path,
3380 * which could be changed by the user. */
3381 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
3382 for (itHD = avsdeHDs.begin();
3383 itHD != avsdeHDs.end();
3384 ++itHD)
3385 {
3386 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
3387 if (vsdeHD->strRef == oit->first)
3388 {
3389 vsdeTargetHD = vsdeHD;
3390 break;
3391 }
3392 }
3393 if (!vsdeTargetHD)
3394 {
3395 /* possible case if a disk image belongs to other virtual system (OVF package with multiple VMs inside) */
3396 Log1Warning(("OVA/OVF import: Disk image %s was missed during import of VM %s\n",
3397 oit->first.c_str(), vmNameEntry->strOvf.c_str()));
3398 NOREF(vmNameEntry);
3399 ++oit;
3400 continue;
3401 }
3402 }
3403
3404 /*
3405 * preliminary check availability of the image
3406 * This step is useful if image is placed in the OVA (TAR) package
3407 */
3408
3409 Utf8Str name = i_applianceIOName(applianceIOTar);
3410
3411 if (strncmp(pStorage->pVDImageIfaces->pszInterfaceName, name.c_str(), name.length()) == 0)
3412 {
3413 /* It means that we possibly have imported the storage earlier on the previous loop steps*/
3414 std::set<RTCString>::const_iterator h = disksResolvedNames.find(diCurrent.strHref);
3415 if (h != disksResolvedNames.end())
3416 {
3417 /* Yes, disk name was found, we can skip it*/
3418 ++oit;
3419 continue;
3420 }
3421
3422 RTCString availableImage(diCurrent.strHref);
3423
3424 rc = i_preCheckImageAvailability(pStorage, availableImage);
3425
3426 if (SUCCEEDED(rc))
3427 {
3428 /* current opened file isn't the same as passed one */
3429 if(availableImage.compare(diCurrent.strHref, Utf8Str::CaseInsensitive) != 0)
3430 {
3431 // availableImage contains the disk identifier (e.g. "vmdisk1"), which should exist
3432 // in the virtual system's disks map under that ID and also in the global images map
3433 // and find the disk from the OVF's disk list
3434 ovf::DiskImagesMap::const_iterator itDiskImage = stack.mapDisks.begin();
3435 while (++itDiskImage != stack.mapDisks.end())
3436 {
3437 if(itDiskImage->second.strHref.compare(availableImage, Utf8Str::CaseInsensitive) == 0 )
3438 break;
3439 }
3440 if (itDiskImage == stack.mapDisks.end())
3441 {
3442 throw setError(E_FAIL,
3443 tr("Internal inconsistency looking up disk image '%s'. "
3444 "Check compliance OVA package structure and file names "
3445 "references in the section <References> in the OVF file."),
3446 availableImage.c_str());
3447 }
3448
3449 /* replace with a new found disk image */
3450 diCurrent = *(&itDiskImage->second);
3451
3452 /*
3453 * Again iterate over all given disk images of the virtual system
3454 * disks description using the found disk image
3455 */
3456 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
3457 for (itHD = avsdeHDs.begin();
3458 itHD != avsdeHDs.end();
3459 ++itHD)
3460 {
3461 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
3462 if (vsdeHD->strRef == diCurrent.strDiskId)
3463 {
3464 vsdeTargetHD = vsdeHD;
3465 break;
3466 }
3467 }
3468 if (!vsdeTargetHD)
3469 /*
3470 * in this case it's an error because something wrong with OVF description file.
3471 * May be VBox imports OVA package with wrong file sequence inside the archive.
3472 */
3473 throw setError(E_FAIL,
3474 tr("Internal inconsistency looking up disk image '%s'"),
3475 diCurrent.strHref.c_str());
3476 }
3477 else
3478 {
3479 ++oit;
3480 }
3481 }
3482 else
3483 {
3484 ++oit;
3485 continue;
3486 }
3487 }
3488 else
3489 {
3490 /* just continue with normal files*/
3491 ++oit;
3492 }
3493
3494 /* Important! to store disk name for the next checks */
3495 disksResolvedNames.insert(diCurrent.strHref);
3496
3497 // there must be an image in the OVF disk structs with the same UUID
3498 bool fFound = false;
3499 Utf8Str strUuid;
3500
3501 // for each storage controller...
3502 for (settings::StorageControllersList::iterator sit = config.storageMachine.llStorageControllers.begin();
3503 sit != config.storageMachine.llStorageControllers.end();
3504 ++sit)
3505 {
3506 settings::StorageController &sc = *sit;
3507
3508 // find the OVF virtual system description entry for this storage controller
3509 switch (sc.storageBus)
3510 {
3511 case StorageBus_SATA:
3512 break;
3513 case StorageBus_SCSI:
3514 break;
3515 case StorageBus_IDE:
3516 break;
3517 case StorageBus_SAS:
3518 break;
3519 }
3520
3521 // for each medium attachment to this controller...
3522 for (settings::AttachedDevicesList::iterator dit = sc.llAttachedDevices.begin();
3523 dit != sc.llAttachedDevices.end();
3524 ++dit)
3525 {
3526 settings::AttachedDevice &d = *dit;
3527
3528 if (d.uuid.isZero())
3529 // empty DVD and floppy media
3530 continue;
3531
3532 // When repairing a broken VirtualBox xml config section (written
3533 // by VirtualBox versions earlier than 3.2.10) assume the disks
3534 // show up in the same order as in the OVF description.
3535 if (fRepairDuplicate)
3536 {
3537 VirtualSystemDescriptionEntry *vsdeHD = *avsdeHDsIt;
3538 ovf::DiskImagesMap::const_iterator itDiskImage = stack.mapDisks.find(vsdeHD->strRef);
3539 if (itDiskImage != stack.mapDisks.end())
3540 {
3541 const ovf::DiskImage &di = itDiskImage->second;
3542 d.uuid = Guid(di.uuidVBox);
3543 }
3544 ++avsdeHDsIt;
3545 }
3546
3547 // convert the Guid to string
3548 strUuid = d.uuid.toString();
3549
3550 if (diCurrent.uuidVBox != strUuid)
3551 {
3552 continue;
3553 }
3554
3555 /*
3556 * step 3: import disk
3557 */
3558 Utf8Str savedVBoxCurrent = vsdeTargetHD->strVBoxCurrent;
3559 ComObjPtr<Medium> pTargetHD;
3560
3561 i_importOneDiskImage(diCurrent,
3562 &vsdeTargetHD->strVBoxCurrent,
3563 pTargetHD,
3564 stack,
3565 pCallbacks,
3566 pStorage);
3567
3568 Bstr hdId;
3569
3570 ComObjPtr<MediumFormat> mediumFormat;
3571 rc = i_findMediumFormatFromDiskImage(diCurrent, mediumFormat);
3572 if (FAILED(rc))
3573 throw rc;
3574
3575 Bstr bstrFormatName;
3576 rc = mediumFormat->COMGETTER(Name)(bstrFormatName.asOutParam());
3577 if (FAILED(rc))
3578 throw rc;
3579
3580 Utf8Str vdf = Utf8Str(bstrFormatName);
3581
3582 if (vdf.compare("RAW", Utf8Str::CaseInsensitive) == 0)
3583 {
3584 ComPtr<IMedium> dvdImage(pTargetHD);
3585
3586 rc = mVirtualBox->OpenMedium(Bstr(vsdeTargetHD->strVBoxCurrent).raw(),
3587 DeviceType_DVD,
3588 AccessMode_ReadWrite,
3589 false,
3590 dvdImage.asOutParam());
3591
3592 if (FAILED(rc)) throw rc;
3593
3594 // ... and replace the old UUID in the machine config with the one of
3595 // the imported disk that was just created
3596 rc = dvdImage->COMGETTER(Id)(hdId.asOutParam());
3597 if (FAILED(rc)) throw rc;
3598 }
3599 else
3600 {
3601 // ... and replace the old UUID in the machine config with the one of
3602 // the imported disk that was just created
3603 rc = pTargetHD->COMGETTER(Id)(hdId.asOutParam());
3604 if (FAILED(rc)) throw rc;
3605 }
3606
3607 /* restore */
3608 vsdeTargetHD->strVBoxCurrent = savedVBoxCurrent;
3609
3610 /*
3611 * 1. saving original UUID for restoring in case of failure.
3612 * 2. replacement of original UUID by new UUID in the current VM config (settings::MachineConfigFile).
3613 */
3614 {
3615 rc = stack.saveOriginalUUIDOfAttachedDevice(d, Utf8Str(hdId));
3616 d.uuid = hdId;
3617 }
3618
3619 fFound = true;
3620 break;
3621 } // for (settings::AttachedDevicesList::const_iterator dit = sc.llAttachedDevices.begin();
3622 } // for (settings::StorageControllersList::const_iterator sit = config.storageMachine.llStorageControllers.begin();
3623
3624 // no disk with such a UUID found:
3625 if (!fFound)
3626 throw setError(E_FAIL,
3627 tr("<vbox:Machine> element in OVF contains a medium attachment for the disk image %s "
3628 "but the OVF describes no such image"),
3629 strUuid.c_str());
3630
3631 ++cImportedDisks;
3632
3633 }// while(oit != stack.mapDisks.end())
3634
3635
3636 /*
3637 * quantity of the imported disks isn't equal to the size of the avsdeHDs list.
3638 */
3639 if(cImportedDisks < avsdeHDs.size())
3640 {
3641 Log1Warning(("Not all disk images were imported for VM %s. Check OVF description file.",
3642 vmNameEntry->strOvf.c_str()));
3643 }
3644
3645 /*
3646 * step 4): create the machine and have it import the config
3647 */
3648
3649 ComObjPtr<Machine> pNewMachine;
3650 rc = pNewMachine.createObject();
3651 if (FAILED(rc)) throw rc;
3652
3653 // this magic constructor fills the new machine object with the MachineConfig
3654 // instance that we created from the vbox:Machine
3655 rc = pNewMachine->init(mVirtualBox,
3656 stack.strNameVBox,// name from OVF preparations; can be suffixed to avoid duplicates
3657 config); // the whole machine config
3658 if (FAILED(rc)) throw rc;
3659
3660 pReturnNewMachine = ComPtr<IMachine>(pNewMachine);
3661
3662 // and register it
3663 rc = mVirtualBox->RegisterMachine(pNewMachine);
3664 if (FAILED(rc)) throw rc;
3665
3666 // store new machine for roll-back in case of errors
3667 Bstr bstrNewMachineId;
3668 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
3669 if (FAILED(rc)) throw rc;
3670 m->llGuidsMachinesCreated.push_back(Guid(bstrNewMachineId));
3671
3672 LogFlowFuncLeave();
3673}
3674
3675void Appliance::i_importMachines(ImportStack &stack,
3676 PVDINTERFACEIO pCallbacks,
3677 PSHASTORAGE pStorage)
3678{
3679 HRESULT rc = S_OK;
3680
3681 // this is safe to access because this thread only gets started
3682 const ovf::OVFReader &reader = *m->pReader;
3683
3684 /*
3685 * get the SHA digest version that was set in accordance with the value of attribute "xmlns:ovf"
3686 * of the element <Envelope> in the OVF file during reading operation. See readFSImpl().
3687 */
3688 pStorage->fSha256 = m->fSha256;
3689
3690 // create a session for the machine + disks we manipulate below
3691 rc = stack.pSession.createInprocObject(CLSID_Session);
3692 if (FAILED(rc)) throw rc;
3693
3694 list<ovf::VirtualSystem>::const_iterator it;
3695 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it1;
3696 /* Iterate through all virtual systems of that appliance */
3697 size_t i = 0;
3698 for (it = reader.m_llVirtualSystems.begin(), it1 = m->virtualSystemDescriptions.begin();
3699 it != reader.m_llVirtualSystems.end() && it1 != m->virtualSystemDescriptions.end();
3700 ++it, ++it1, ++i)
3701 {
3702 const ovf::VirtualSystem &vsysThis = *it;
3703 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it1);
3704
3705 ComPtr<IMachine> pNewMachine;
3706
3707 // there are two ways in which we can create a vbox machine from OVF:
3708 // -- either this OVF was written by vbox 3.2 or later, in which case there is a <vbox:Machine> element
3709 // in the <VirtualSystem>; then the VirtualSystemDescription::Data has a settings::MachineConfigFile
3710 // with all the machine config pretty-parsed;
3711 // -- or this is an OVF from an older vbox or an external source, and then we need to translate the
3712 // VirtualSystemDescriptionEntry and do import work
3713
3714 // Even for the vbox:Machine case, there are a number of configuration items that will be taken from
3715 // the OVF because otherwise the "override import parameters" mechanism in the GUI won't work.
3716
3717 // VM name
3718 std::list<VirtualSystemDescriptionEntry*> vsdeName = vsdescThis->i_findByType(VirtualSystemDescriptionType_Name);
3719 if (vsdeName.size() < 1)
3720 throw setError(VBOX_E_FILE_ERROR,
3721 tr("Missing VM name"));
3722 stack.strNameVBox = vsdeName.front()->strVBoxCurrent;
3723
3724 // have VirtualBox suggest where the filename would be placed so we can
3725 // put the disk images in the same directory
3726 Bstr bstrMachineFilename;
3727 rc = mVirtualBox->ComposeMachineFilename(Bstr(stack.strNameVBox).raw(),
3728 NULL /* aGroup */,
3729 NULL /* aCreateFlags */,
3730 NULL /* aBaseFolder */,
3731 bstrMachineFilename.asOutParam());
3732 if (FAILED(rc)) throw rc;
3733 // and determine the machine folder from that
3734 stack.strMachineFolder = bstrMachineFilename;
3735 stack.strMachineFolder.stripFilename();
3736 LogFunc(("i=%zu strName=%s bstrMachineFilename=%ls\n", i, stack.strNameVBox.c_str(), bstrMachineFilename.raw()));
3737
3738 // guest OS type
3739 std::list<VirtualSystemDescriptionEntry*> vsdeOS;
3740 vsdeOS = vsdescThis->i_findByType(VirtualSystemDescriptionType_OS);
3741 if (vsdeOS.size() < 1)
3742 throw setError(VBOX_E_FILE_ERROR,
3743 tr("Missing guest OS type"));
3744 stack.strOsTypeVBox = vsdeOS.front()->strVBoxCurrent;
3745
3746 // CPU count
3747 std::list<VirtualSystemDescriptionEntry*> vsdeCPU = vsdescThis->i_findByType(VirtualSystemDescriptionType_CPU);
3748 if (vsdeCPU.size() != 1)
3749 throw setError(VBOX_E_FILE_ERROR, tr("CPU count missing"));
3750
3751 stack.cCPUs = vsdeCPU.front()->strVBoxCurrent.toUInt32();
3752 // We need HWVirt & IO-APIC if more than one CPU is requested
3753 if (stack.cCPUs > 1)
3754 {
3755 stack.fForceHWVirt = true;
3756 stack.fForceIOAPIC = true;
3757 }
3758
3759 // RAM
3760 std::list<VirtualSystemDescriptionEntry*> vsdeRAM = vsdescThis->i_findByType(VirtualSystemDescriptionType_Memory);
3761 if (vsdeRAM.size() != 1)
3762 throw setError(VBOX_E_FILE_ERROR, tr("RAM size missing"));
3763 stack.ulMemorySizeMB = (ULONG)vsdeRAM.front()->strVBoxCurrent.toUInt64();
3764
3765#ifdef VBOX_WITH_USB
3766 // USB controller
3767 std::list<VirtualSystemDescriptionEntry*> vsdeUSBController =
3768 vsdescThis->i_findByType(VirtualSystemDescriptionType_USBController);
3769 // USB support is enabled if there's at least one such entry; to disable USB support,
3770 // the type of the USB item would have been changed to "ignore"
3771 stack.fUSBEnabled = !vsdeUSBController.empty();
3772#endif
3773 // audio adapter
3774 std::list<VirtualSystemDescriptionEntry*> vsdeAudioAdapter =
3775 vsdescThis->i_findByType(VirtualSystemDescriptionType_SoundCard);
3776 /* @todo: we support one audio adapter only */
3777 if (!vsdeAudioAdapter.empty())
3778 stack.strAudioAdapter = vsdeAudioAdapter.front()->strVBoxCurrent;
3779
3780 // for the description of the new machine, always use the OVF entry, the user may have changed it in the import config
3781 std::list<VirtualSystemDescriptionEntry*> vsdeDescription =
3782 vsdescThis->i_findByType(VirtualSystemDescriptionType_Description);
3783 if (!vsdeDescription.empty())
3784 stack.strDescription = vsdeDescription.front()->strVBoxCurrent;
3785
3786 // import vbox:machine or OVF now
3787 if (vsdescThis->m->pConfig)
3788 // vbox:Machine config
3789 i_importVBoxMachine(vsdescThis, pNewMachine, stack, pCallbacks, pStorage);
3790 else
3791 // generic OVF config
3792 i_importMachineGeneric(vsysThis, vsdescThis, pNewMachine, stack, pCallbacks, pStorage);
3793
3794 } // for (it = pAppliance->m->llVirtualSystems.begin() ...
3795}
3796
3797HRESULT Appliance::ImportStack::saveOriginalUUIDOfAttachedDevice(settings::AttachedDevice &device,
3798 const Utf8Str &newlyUuid)
3799{
3800 HRESULT rc = S_OK;
3801
3802 /* save for restoring */
3803 mapNewUUIDsToOriginalUUIDs.insert(std::make_pair(newlyUuid, device.uuid.toString()));
3804
3805 return rc;
3806}
3807
3808HRESULT Appliance::ImportStack::restoreOriginalUUIDOfAttachedDevice(settings::MachineConfigFile *config)
3809{
3810 HRESULT rc = S_OK;
3811
3812 settings::StorageControllersList &llControllers = config->storageMachine.llStorageControllers;
3813 settings::StorageControllersList::iterator itscl;
3814 for (itscl = llControllers.begin();
3815 itscl != llControllers.end();
3816 ++itscl)
3817 {
3818 settings::AttachedDevicesList &llAttachments = itscl->llAttachedDevices;
3819 settings::AttachedDevicesList::iterator itadl = llAttachments.begin();
3820 while (itadl != llAttachments.end())
3821 {
3822 std::map<Utf8Str , Utf8Str>::iterator it =
3823 mapNewUUIDsToOriginalUUIDs.find(itadl->uuid.toString());
3824 if(it!=mapNewUUIDsToOriginalUUIDs.end())
3825 {
3826 Utf8Str uuidOriginal = it->second;
3827 itadl->uuid = Guid(uuidOriginal);
3828 mapNewUUIDsToOriginalUUIDs.erase(it->first);
3829 }
3830 ++itadl;
3831 }
3832 }
3833
3834 return rc;
3835}
3836
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