VirtualBox

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

Last change on this file since 46518 was 46518, checked in by vboxsync, 12 years ago

Export/import OVA/OVF package supports ISO images. The problem with the wrong search files in the archive has been resolved. (see #5429). 2 new elements SASD and EPASD were added in the OVF XML file structure (see #6022).

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