VirtualBox

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

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

issue 5429. Support CD/DVD images attached to IDE/SATA during OVF import/export.

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