VirtualBox

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

Last change on this file since 50199 was 50199, checked in by vboxsync, 11 years ago

Corrected misleading helper function names: s/ShaReadBuf/readFileIntoBuffer/, s/ShaWriteBuf/writeBufferToFile/

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

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