VirtualBox

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

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

pr6022. Second variant of support GZIP files for OVA appliance.

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