VirtualBox

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

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

Main: s/Vbox/VBox/g s/VB/VBox/g

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