VirtualBox

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

Last change on this file since 50002 was 49951, checked in by vboxsync, 11 years ago

6813 - stage 5 - Make use of server side API wrapper code in all interfaces

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

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