VirtualBox

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

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

Appliance::i_importFSOVF: Typo, should use RTManifestEntrySetAttr not RTManifestSetAttr.

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