VirtualBox

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

Last change on this file since 52267 was 52267, checked in by vboxsync, 10 years ago

unused param, variables warnings.

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette