VirtualBox

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

Last change on this file since 38455 was 38455, checked in by vboxsync, 14 years ago

Main-OVA: fix importing of renamed OVA files

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