VirtualBox

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

Last change on this file since 42038 was 42038, checked in by vboxsync, 13 years ago

Main/ApplianceImport: Don't use the SHA VFS layer if there is no manifest to check against

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