VirtualBox

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

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

Main/Appliance: Don't crash during import if the client forgot to call Appliance::interpret (public #10845)

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

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