VirtualBox

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

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

Main: a couple of whitespace fixes

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

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