VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/ApplianceImplExport.cpp@ 65264

Last change on this file since 65264 was 65120, checked in by vboxsync, 8 years ago

Main: doxygen fixes

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 104.6 KB
Line 
1/* $Id: ApplianceImplExport.cpp 65120 2017-01-04 17:10:35Z vboxsync $ */
2/** @file
3 * IAppliance and IVirtualSystem COM class implementations.
4 */
5
6/*
7 * Copyright (C) 2008-2016 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#include <iprt/path.h>
19#include <iprt/dir.h>
20#include <iprt/param.h>
21#include <iprt/s3.h>
22#include <iprt/manifest.h>
23#include <iprt/tar.h>
24#include <iprt/stream.h>
25
26#include <VBox/version.h>
27
28#include "ApplianceImpl.h"
29#include "VirtualBoxImpl.h"
30#include "ProgressImpl.h"
31#include "MachineImpl.h"
32#include "MediumImpl.h"
33#include "MediumFormatImpl.h"
34#include "Global.h"
35#include "SystemPropertiesImpl.h"
36
37#include "AutoCaller.h"
38#include "Logging.h"
39
40#include "ApplianceImplPrivate.h"
41
42using namespace std;
43
44////////////////////////////////////////////////////////////////////////////////
45//
46// IMachine public methods
47//
48////////////////////////////////////////////////////////////////////////////////
49
50// This code is here so we won't have to include the appliance headers in the
51// IMachine implementation, and we also need to access private appliance data.
52
53/**
54* Public method implementation.
55* @param aAppliance Appliance object.
56* @param aLocation Where to store the appliance.
57* @param aDescription Appliance description.
58* @return
59*/
60HRESULT Machine::exportTo(const ComPtr<IAppliance> &aAppliance, const com::Utf8Str &aLocation,
61 ComPtr<IVirtualSystemDescription> &aDescription)
62{
63 HRESULT rc = S_OK;
64
65 if (!aAppliance)
66 return E_POINTER;
67
68 ComObjPtr<VirtualSystemDescription> pNewDesc;
69
70 try
71 {
72 IAppliance *iAppliance = aAppliance;
73 Appliance *pAppliance = static_cast<Appliance*>(iAppliance);
74
75 LocationInfo locInfo;
76 i_parseURI(aLocation, locInfo);
77 // create a new virtual system to store in the appliance
78 rc = pNewDesc.createObject();
79 if (FAILED(rc)) throw rc;
80 rc = pNewDesc->init();
81 if (FAILED(rc)) throw rc;
82
83 // store the machine object so we can dump the XML in Appliance::Write()
84 pNewDesc->m->pMachine = this;
85
86 // first, call the COM methods, as they request locks
87 BOOL fUSBEnabled = FALSE;
88 com::SafeIfaceArray<IUSBController> usbControllers;
89 rc = COMGETTER(USBControllers)(ComSafeArrayAsOutParam(usbControllers));
90 if (SUCCEEDED(rc))
91 {
92 for (unsigned i = 0; i < usbControllers.size(); ++i)
93 {
94 USBControllerType_T enmType;
95
96 rc = usbControllers[i]->COMGETTER(Type)(&enmType);
97 if (FAILED(rc)) throw rc;
98
99 if (enmType == USBControllerType_OHCI)
100 fUSBEnabled = TRUE;
101 }
102 }
103
104 // request the machine lock while accessing internal members
105 AutoReadLock alock1(this COMMA_LOCKVAL_SRC_POS);
106
107 ComPtr<IAudioAdapter> pAudioAdapter = mAudioAdapter;
108 BOOL fAudioEnabled;
109 rc = pAudioAdapter->COMGETTER(Enabled)(&fAudioEnabled);
110 if (FAILED(rc)) throw rc;
111 AudioControllerType_T audioController;
112 rc = pAudioAdapter->COMGETTER(AudioController)(&audioController);
113 if (FAILED(rc)) throw rc;
114
115 // get name
116 Utf8Str strVMName = mUserData->s.strName;
117 // get description
118 Utf8Str strDescription = mUserData->s.strDescription;
119 // get guest OS
120 Utf8Str strOsTypeVBox = mUserData->s.strOsType;
121 // CPU count
122 uint32_t cCPUs = mHWData->mCPUCount;
123 // memory size in MB
124 uint32_t ulMemSizeMB = mHWData->mMemorySize;
125 // VRAM size?
126 // BIOS settings?
127 // 3D acceleration enabled?
128 // hardware virtualization enabled?
129 // nested paging enabled?
130 // HWVirtExVPIDEnabled?
131 // PAEEnabled?
132 // Long mode enabled?
133 BOOL fLongMode;
134 rc = GetCPUProperty(CPUPropertyType_LongMode, &fLongMode);
135 if (FAILED(rc)) throw rc;
136
137 // snapshotFolder?
138 // VRDPServer?
139
140 /* Guest OS type */
141 ovf::CIMOSType_T cim = convertVBoxOSType2CIMOSType(strOsTypeVBox.c_str(), fLongMode);
142 pNewDesc->i_addEntry(VirtualSystemDescriptionType_OS,
143 "",
144 Utf8StrFmt("%RI32", cim),
145 strOsTypeVBox);
146
147 /* VM name */
148 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Name,
149 "",
150 strVMName,
151 strVMName);
152
153 // description
154 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Description,
155 "",
156 strDescription,
157 strDescription);
158
159 /* CPU count*/
160 Utf8Str strCpuCount = Utf8StrFmt("%RI32", cCPUs);
161 pNewDesc->i_addEntry(VirtualSystemDescriptionType_CPU,
162 "",
163 strCpuCount,
164 strCpuCount);
165
166 /* Memory */
167 Utf8Str strMemory = Utf8StrFmt("%RI64", (uint64_t)ulMemSizeMB * _1M);
168 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Memory,
169 "",
170 strMemory,
171 strMemory);
172
173 // the one VirtualBox IDE controller has two channels with two ports each, which is
174 // considered two IDE controllers with two ports each by OVF, so export it as two
175 int32_t lIDEControllerPrimaryIndex = 0;
176 int32_t lIDEControllerSecondaryIndex = 0;
177 int32_t lSATAControllerIndex = 0;
178 int32_t lSCSIControllerIndex = 0;
179
180 /* Fetch all available storage controllers */
181 com::SafeIfaceArray<IStorageController> nwControllers;
182 rc = COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(nwControllers));
183 if (FAILED(rc)) throw rc;
184
185 ComPtr<IStorageController> pIDEController;
186 ComPtr<IStorageController> pSATAController;
187 ComPtr<IStorageController> pSCSIController;
188 ComPtr<IStorageController> pSASController;
189 for (size_t j = 0; j < nwControllers.size(); ++j)
190 {
191 StorageBus_T eType;
192 rc = nwControllers[j]->COMGETTER(Bus)(&eType);
193 if (FAILED(rc)) throw rc;
194 if ( eType == StorageBus_IDE
195 && pIDEController.isNull())
196 pIDEController = nwControllers[j];
197 else if ( eType == StorageBus_SATA
198 && pSATAController.isNull())
199 pSATAController = nwControllers[j];
200 else if ( eType == StorageBus_SCSI
201 && pSATAController.isNull())
202 pSCSIController = nwControllers[j];
203 else if ( eType == StorageBus_SAS
204 && pSASController.isNull())
205 pSASController = nwControllers[j];
206 }
207
208// <const name="HardDiskControllerIDE" value="6" />
209 if (!pIDEController.isNull())
210 {
211 StorageControllerType_T ctlr;
212 rc = pIDEController->COMGETTER(ControllerType)(&ctlr);
213 if (FAILED(rc)) throw rc;
214
215 Utf8Str strVBox;
216 switch (ctlr)
217 {
218 case StorageControllerType_PIIX3: strVBox = "PIIX3"; break;
219 case StorageControllerType_PIIX4: strVBox = "PIIX4"; break;
220 case StorageControllerType_ICH6: strVBox = "ICH6"; break;
221 default: break; /* Shut up MSC. */
222 }
223
224 if (strVBox.length())
225 {
226 lIDEControllerPrimaryIndex = (int32_t)pNewDesc->m->maDescriptions.size();
227 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
228 Utf8StrFmt("%d", lIDEControllerPrimaryIndex), // strRef
229 strVBox, // aOvfValue
230 strVBox); // aVBoxValue
231 lIDEControllerSecondaryIndex = lIDEControllerPrimaryIndex + 1;
232 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
233 Utf8StrFmt("%d", lIDEControllerSecondaryIndex),
234 strVBox,
235 strVBox);
236 }
237 }
238
239// <const name="HardDiskControllerSATA" value="7" />
240 if (!pSATAController.isNull())
241 {
242 Utf8Str strVBox = "AHCI";
243 lSATAControllerIndex = (int32_t)pNewDesc->m->maDescriptions.size();
244 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerSATA,
245 Utf8StrFmt("%d", lSATAControllerIndex),
246 strVBox,
247 strVBox);
248 }
249
250// <const name="HardDiskControllerSCSI" value="8" />
251 if (!pSCSIController.isNull())
252 {
253 StorageControllerType_T ctlr;
254 rc = pSCSIController->COMGETTER(ControllerType)(&ctlr);
255 if (SUCCEEDED(rc))
256 {
257 Utf8Str strVBox = "LsiLogic"; // the default in VBox
258 switch (ctlr)
259 {
260 case StorageControllerType_LsiLogic: strVBox = "LsiLogic"; break;
261 case StorageControllerType_BusLogic: strVBox = "BusLogic"; break;
262 default: break; /* Shut up MSC. */
263 }
264 lSCSIControllerIndex = (int32_t)pNewDesc->m->maDescriptions.size();
265 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerSCSI,
266 Utf8StrFmt("%d", lSCSIControllerIndex),
267 strVBox,
268 strVBox);
269 }
270 else
271 throw rc;
272 }
273
274 if (!pSASController.isNull())
275 {
276 // VirtualBox considers the SAS controller a class of its own but in OVF
277 // it should be a SCSI controller
278 Utf8Str strVBox = "LsiLogicSas";
279 lSCSIControllerIndex = (int32_t)pNewDesc->m->maDescriptions.size();
280 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskControllerSAS,
281 Utf8StrFmt("%d", lSCSIControllerIndex),
282 strVBox,
283 strVBox);
284 }
285
286// <const name="HardDiskImage" value="9" />
287// <const name="Floppy" value="18" />
288// <const name="CDROM" value="19" />
289
290 MediaData::AttachmentList::iterator itA;
291 for (itA = mMediaData->mAttachments.begin();
292 itA != mMediaData->mAttachments.end();
293 ++itA)
294 {
295 ComObjPtr<MediumAttachment> pHDA = *itA;
296
297 // the attachment's data
298 ComPtr<IMedium> pMedium;
299 ComPtr<IStorageController> ctl;
300 Bstr controllerName;
301
302 rc = pHDA->COMGETTER(Controller)(controllerName.asOutParam());
303 if (FAILED(rc)) throw rc;
304
305 rc = GetStorageControllerByName(controllerName.raw(), ctl.asOutParam());
306 if (FAILED(rc)) throw rc;
307
308 StorageBus_T storageBus;
309 DeviceType_T deviceType;
310 LONG lChannel;
311 LONG lDevice;
312
313 rc = ctl->COMGETTER(Bus)(&storageBus);
314 if (FAILED(rc)) throw rc;
315
316 rc = pHDA->COMGETTER(Type)(&deviceType);
317 if (FAILED(rc)) throw rc;
318
319 rc = pHDA->COMGETTER(Medium)(pMedium.asOutParam());
320 if (FAILED(rc)) throw rc;
321
322 rc = pHDA->COMGETTER(Port)(&lChannel);
323 if (FAILED(rc)) throw rc;
324
325 rc = pHDA->COMGETTER(Device)(&lDevice);
326 if (FAILED(rc)) throw rc;
327
328 Utf8Str strTargetImageName;
329 Utf8Str strLocation;
330 LONG64 llSize = 0;
331
332 if ( deviceType == DeviceType_HardDisk
333 && pMedium)
334 {
335 Bstr bstrLocation;
336
337 rc = pMedium->COMGETTER(Location)(bstrLocation.asOutParam());
338 if (FAILED(rc)) throw rc;
339 strLocation = bstrLocation;
340
341 // find the source's base medium for two things:
342 // 1) we'll use its name to determine the name of the target disk, which is readable,
343 // as opposed to the UUID filename of a differencing image, if pMedium is one
344 // 2) we need the size of the base image so we can give it to addEntry(), and later
345 // on export, the progress will be based on that (and not the diff image)
346 ComPtr<IMedium> pBaseMedium;
347 rc = pMedium->COMGETTER(Base)(pBaseMedium.asOutParam());
348 // returns pMedium if there are no diff images
349 if (FAILED(rc)) throw rc;
350
351 Utf8Str strName = Utf8Str(locInfo.strPath).stripPath().stripSuffix();
352 strTargetImageName = Utf8StrFmt("%s-disk%d.vmdk", strName.c_str(), ++pAppliance->m->cDisks);
353 if (strTargetImageName.length() > RTTAR_NAME_MAX)
354 throw setError(VBOX_E_NOT_SUPPORTED,
355 tr("Cannot attach disk '%s' -- file name too long"), strTargetImageName.c_str());
356
357 // force reading state, or else size will be returned as 0
358 MediumState_T ms;
359 rc = pBaseMedium->RefreshState(&ms);
360 if (FAILED(rc)) throw rc;
361
362 rc = pBaseMedium->COMGETTER(Size)(&llSize);
363 if (FAILED(rc)) throw rc;
364
365 /* If the medium is encrypted add the key identifier to the list. */
366 IMedium *iBaseMedium = pBaseMedium;
367 Medium *pBase = static_cast<Medium*>(iBaseMedium);
368 const com::Utf8Str strKeyId = pBase->i_getKeyId();
369 if (!strKeyId.isEmpty())
370 {
371 IMedium *iMedium = pMedium;
372 Medium *pMed = static_cast<Medium*>(iMedium);
373 com::Guid mediumUuid = pMed->i_getId();
374 bool fKnown = false;
375
376 /* Check whether the ID is already in our sequence, add it otherwise. */
377 for (unsigned i = 0; i < pAppliance->m->m_vecPasswordIdentifiers.size(); i++)
378 {
379 if (strKeyId.equals(pAppliance->m->m_vecPasswordIdentifiers[i]))
380 {
381 fKnown = true;
382 break;
383 }
384 }
385
386 if (!fKnown)
387 {
388 GUIDVEC vecMediumIds;
389
390 vecMediumIds.push_back(mediumUuid);
391 pAppliance->m->m_vecPasswordIdentifiers.push_back(strKeyId);
392 pAppliance->m->m_mapPwIdToMediumIds.insert(std::pair<com::Utf8Str, GUIDVEC>(strKeyId, vecMediumIds));
393 }
394 else
395 {
396 std::map<com::Utf8Str, GUIDVEC>::iterator it = pAppliance->m->m_mapPwIdToMediumIds.find(strKeyId);
397 if (it == pAppliance->m->m_mapPwIdToMediumIds.end())
398 throw setError(E_FAIL, tr("Internal error adding a medium UUID to the map"));
399 it->second.push_back(mediumUuid);
400 }
401 }
402 }
403 else if ( deviceType == DeviceType_DVD
404 && pMedium)
405 {
406 /*
407 * check the minimal rules to grant access to export an image
408 * 1. no host drive CD/DVD image
409 * 2. the image must be accessible and readable
410 * 3. only ISO image is exported
411 */
412
413 //1. no host drive CD/DVD image
414 BOOL fHostDrive = false;
415 rc = pMedium->COMGETTER(HostDrive)(&fHostDrive);
416 if (FAILED(rc)) throw rc;
417
418 if(fHostDrive)
419 continue;
420
421 //2. the image must be accessible and readable
422 MediumState_T ms;
423 rc = pMedium->RefreshState(&ms);
424 if (FAILED(rc)) throw rc;
425
426 if (ms != MediumState_Created)
427 continue;
428
429 //3. only ISO image is exported
430 Bstr bstrLocation;
431 rc = pMedium->COMGETTER(Location)(bstrLocation.asOutParam());
432 if (FAILED(rc)) throw rc;
433
434 strLocation = bstrLocation;
435
436 Utf8Str ext = strLocation;
437 ext.assignEx(RTPathSuffix(ext.c_str()));//returns extension with dot (".iso")
438
439 int eq = ext.compare(".iso", Utf8Str::CaseInsensitive);
440 if (eq != 0)
441 continue;
442
443 Utf8Str strName = Utf8Str(locInfo.strPath).stripPath().stripSuffix();
444 strTargetImageName = Utf8StrFmt("%s-disk%d.iso", strName.c_str(), ++pAppliance->m->cDisks);
445 if (strTargetImageName.length() > RTTAR_NAME_MAX)
446 throw setError(VBOX_E_NOT_SUPPORTED,
447 tr("Cannot attach image '%s' -- file name too long"), strTargetImageName.c_str());
448
449 rc = pMedium->COMGETTER(Size)(&llSize);
450 if (FAILED(rc)) throw rc;
451 }
452 // and how this translates to the virtual system
453 int32_t lControllerVsys = 0;
454 LONG lChannelVsys;
455
456 switch (storageBus)
457 {
458 case StorageBus_IDE:
459 // this is the exact reverse to what we're doing in Appliance::taskThreadImportMachines,
460 // and it must be updated when that is changed!
461 // Before 3.2 we exported one IDE controller with channel 0-3, but we now maintain
462 // compatibility with what VMware does and export two IDE controllers with two channels each
463
464 if (lChannel == 0 && lDevice == 0) // primary master
465 {
466 lControllerVsys = lIDEControllerPrimaryIndex;
467 lChannelVsys = 0;
468 }
469 else if (lChannel == 0 && lDevice == 1) // primary slave
470 {
471 lControllerVsys = lIDEControllerPrimaryIndex;
472 lChannelVsys = 1;
473 }
474 else if (lChannel == 1 && lDevice == 0) // secondary master; by default this is the CD-ROM but
475 // as of VirtualBox 3.1 that can change
476 {
477 lControllerVsys = lIDEControllerSecondaryIndex;
478 lChannelVsys = 0;
479 }
480 else if (lChannel == 1 && lDevice == 1) // secondary slave
481 {
482 lControllerVsys = lIDEControllerSecondaryIndex;
483 lChannelVsys = 1;
484 }
485 else
486 throw setError(VBOX_E_NOT_SUPPORTED,
487 tr("Cannot handle medium attachment: channel is %d, device is %d"), lChannel, lDevice);
488 break;
489
490 case StorageBus_SATA:
491 lChannelVsys = lChannel; // should be between 0 and 29
492 lControllerVsys = lSATAControllerIndex;
493 break;
494
495 case StorageBus_SCSI:
496 case StorageBus_SAS:
497 lChannelVsys = lChannel; // should be between 0 and 15
498 lControllerVsys = lSCSIControllerIndex;
499 break;
500
501 case StorageBus_Floppy:
502 lChannelVsys = 0;
503 lControllerVsys = 0;
504 break;
505
506 default:
507 throw setError(VBOX_E_NOT_SUPPORTED,
508 tr("Cannot handle medium attachment: storageBus is %d, channel is %d, device is %d"),
509 storageBus, lChannel, lDevice);
510 break;
511 }
512
513 Utf8StrFmt strExtra("controller=%RI32;channel=%RI32", lControllerVsys, lChannelVsys);
514 Utf8Str strEmpty;
515
516 switch (deviceType)
517 {
518 case DeviceType_HardDisk:
519 Log(("Adding VirtualSystemDescriptionType_HardDiskImage, disk size: %RI64\n", llSize));
520 pNewDesc->i_addEntry(VirtualSystemDescriptionType_HardDiskImage,
521 strTargetImageName, // disk ID: let's use the name
522 strTargetImageName, // OVF value:
523 strLocation, // vbox value: media path
524 (uint32_t)(llSize / _1M),
525 strExtra);
526 break;
527
528 case DeviceType_DVD:
529 Log(("Adding VirtualSystemDescriptionType_CDROM, disk size: %RI64\n", llSize));
530 pNewDesc->i_addEntry(VirtualSystemDescriptionType_CDROM,
531 strTargetImageName, // disk ID
532 strTargetImageName, // OVF value
533 strLocation, // vbox value
534 (uint32_t)(llSize / _1M),// ulSize
535 strExtra);
536 break;
537
538 case DeviceType_Floppy:
539 pNewDesc->i_addEntry(VirtualSystemDescriptionType_Floppy,
540 strEmpty, // disk ID
541 strEmpty, // OVF value
542 strEmpty, // vbox value
543 1, // ulSize
544 strExtra);
545 break;
546
547 default: break; /* Shut up MSC. */
548 }
549 }
550
551// <const name="NetworkAdapter" />
552 uint32_t maxNetworkAdapters = Global::getMaxNetworkAdapters(i_getChipsetType());
553 size_t a;
554 for (a = 0; a < maxNetworkAdapters; ++a)
555 {
556 ComPtr<INetworkAdapter> pNetworkAdapter;
557 BOOL fEnabled;
558 NetworkAdapterType_T adapterType;
559 NetworkAttachmentType_T attachmentType;
560
561 rc = GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
562 if (FAILED(rc)) throw rc;
563 /* Enable the network card & set the adapter type */
564 rc = pNetworkAdapter->COMGETTER(Enabled)(&fEnabled);
565 if (FAILED(rc)) throw rc;
566
567 if (fEnabled)
568 {
569 rc = pNetworkAdapter->COMGETTER(AdapterType)(&adapterType);
570 if (FAILED(rc)) throw rc;
571
572 rc = pNetworkAdapter->COMGETTER(AttachmentType)(&attachmentType);
573 if (FAILED(rc)) throw rc;
574
575 Utf8Str strAttachmentType = convertNetworkAttachmentTypeToString(attachmentType);
576 pNewDesc->i_addEntry(VirtualSystemDescriptionType_NetworkAdapter,
577 "", // ref
578 strAttachmentType, // orig
579 Utf8StrFmt("%RI32", (uint32_t)adapterType), // conf
580 0,
581 Utf8StrFmt("type=%s", strAttachmentType.c_str())); // extra conf
582 }
583 }
584
585// <const name="USBController" />
586#ifdef VBOX_WITH_USB
587 if (fUSBEnabled)
588 pNewDesc->i_addEntry(VirtualSystemDescriptionType_USBController, "", "", "");
589#endif /* VBOX_WITH_USB */
590
591// <const name="SoundCard" />
592 if (fAudioEnabled)
593 pNewDesc->i_addEntry(VirtualSystemDescriptionType_SoundCard,
594 "",
595 "ensoniq1371", // this is what OVFTool writes and VMware supports
596 Utf8StrFmt("%RI32", audioController));
597
598 /* We return the new description to the caller */
599 ComPtr<IVirtualSystemDescription> copy(pNewDesc);
600 copy.queryInterfaceTo(aDescription.asOutParam());
601
602 AutoWriteLock alock(pAppliance COMMA_LOCKVAL_SRC_POS);
603 // finally, add the virtual system to the appliance
604 pAppliance->m->virtualSystemDescriptions.push_back(pNewDesc);
605 }
606 catch(HRESULT arc)
607 {
608 rc = arc;
609 }
610
611 return rc;
612}
613
614////////////////////////////////////////////////////////////////////////////////
615//
616// IAppliance public methods
617//
618////////////////////////////////////////////////////////////////////////////////
619
620/**
621 * Public method implementation.
622 * @param aFormat Appliance format.
623 * @param aOptions Export options.
624 * @param aPath Path to write the appliance to.
625 * @param aProgress Progress object.
626 * @return
627 */
628HRESULT Appliance::write(const com::Utf8Str &aFormat,
629 const std::vector<ExportOptions_T> &aOptions,
630 const com::Utf8Str &aPath,
631 ComPtr<IProgress> &aProgress)
632{
633 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
634
635 m->optListExport.clear();
636 if (aOptions.size())
637 {
638 for (size_t i = 0; i < aOptions.size(); ++i)
639 {
640 m->optListExport.insert(i, aOptions[i]);
641 }
642 }
643
644// AssertReturn(!(m->optListExport.contains(ExportOptions_CreateManifest)
645// && m->optListExport.contains(ExportOptions_ExportDVDImages)), E_INVALIDARG);
646
647 m->fExportISOImages = m->optListExport.contains(ExportOptions_ExportDVDImages);
648
649 if (!m->fExportISOImages)/* remove all ISO images from VirtualSystemDescription */
650 {
651 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
652 for (it = m->virtualSystemDescriptions.begin();
653 it != m->virtualSystemDescriptions.end();
654 ++it)
655 {
656 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
657 std::list<VirtualSystemDescriptionEntry*> skipped = vsdescThis->i_findByType(VirtualSystemDescriptionType_CDROM);
658 std::list<VirtualSystemDescriptionEntry*>:: iterator pItSkipped = skipped.begin();
659 while (pItSkipped != skipped.end())
660 {
661 (*pItSkipped)->skipIt = true;
662 ++pItSkipped;
663 }
664 }
665 }
666
667 // do not allow entering this method if the appliance is busy reading or writing
668 if (!i_isApplianceIdle())
669 return E_ACCESSDENIED;
670
671 // see if we can handle this file; for now we insist it has an ".ovf" extension
672 if (!( aPath.endsWith(".ovf", Utf8Str::CaseInsensitive)
673 || aPath.endsWith(".ova", Utf8Str::CaseInsensitive)))
674 return setError(VBOX_E_FILE_ERROR,
675 tr("Appliance file must have .ovf or .ova extension"));
676
677 m->fManifest = m->optListExport.contains(ExportOptions_CreateManifest);
678
679 ovf::OVFVersion_T ovfF;
680 if (aFormat == "ovf-0.9")
681 {
682 ovfF = ovf::OVFVersion_0_9;
683 }
684 else if (aFormat == "ovf-1.0")
685 {
686 ovfF = ovf::OVFVersion_1_0;
687 }
688 else if (aFormat == "ovf-2.0")
689 {
690 ovfF = ovf::OVFVersion_2_0;
691 }
692 else
693 return setError(VBOX_E_FILE_ERROR,
694 tr("Invalid format \"%s\" specified"), aFormat.c_str());
695
696 /* Check whether all passwords are supplied or error out. */
697 if (m->m_cPwProvided < m->m_vecPasswordIdentifiers.size())
698 return setError(VBOX_E_INVALID_OBJECT_STATE,
699 tr("Appliance export failed because not all passwords were provided for all encrypted media"));
700
701 /* as of OVF 2.0 we have to use SHA256 */
702 m->fSha256 = ovfF >= ovf::OVFVersion_2_0;
703
704 ComObjPtr<Progress> progress;
705 HRESULT rc = S_OK;
706 try
707 {
708 /* Parse all necessary info out of the URI */
709 i_parseURI(aPath, m->locInfo);
710 rc = i_writeImpl(ovfF, m->locInfo, progress);
711 }
712 catch (HRESULT aRC)
713 {
714 rc = aRC;
715 }
716
717 if (SUCCEEDED(rc))
718 /* Return progress to the caller */
719 progress.queryInterfaceTo(aProgress.asOutParam());
720
721 return rc;
722}
723
724////////////////////////////////////////////////////////////////////////////////
725//
726// Appliance private methods
727//
728////////////////////////////////////////////////////////////////////////////////
729
730/*******************************************************************************
731 * Export stuff
732 ******************************************************************************/
733
734/**
735 * Implementation for writing out the OVF to disk. This starts a new thread which will call
736 * Appliance::taskThreadWriteOVF().
737 *
738 * This is in a separate private method because it is used from two locations:
739 *
740 * 1) from the public Appliance::Write().
741 *
742 * 2) in a second worker thread; in that case, Appliance::Write() called Appliance::i_writeImpl(), which
743 * called Appliance::i_writeFSOVA(), which called Appliance::i_writeImpl(), which then called this again.
744 *
745 * @param aFormat
746 * @param aLocInfo
747 * @param aProgress
748 * @return
749 */
750HRESULT Appliance::i_writeImpl(ovf::OVFVersion_T aFormat, const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
751{
752 HRESULT rc;
753 try
754 {
755 rc = i_setUpProgress(aProgress,
756 BstrFmt(tr("Export appliance '%s'"), aLocInfo.strPath.c_str()),
757 (aLocInfo.storageType == VFSType_File) ? WriteFile : WriteS3);
758
759 /* Initialize our worker task */
760 TaskOVF* task = NULL;
761 try
762 {
763 task = new TaskOVF(this, TaskOVF::Write, aLocInfo, aProgress);
764 }
765 catch(...)
766 {
767 delete task;
768 throw rc = setError(VBOX_E_OBJECT_NOT_FOUND,
769 tr("Could not create TaskOVF object for for writing out the OVF to disk"));
770 }
771
772 /* The OVF version to write */
773 task->enFormat = aFormat;
774
775 rc = task->createThread();
776 if (FAILED(rc)) throw rc;
777
778 }
779 catch (HRESULT aRC)
780 {
781 rc = aRC;
782 }
783
784 return rc;
785}
786
787/**
788 * Called from Appliance::i_writeFS() for creating a XML document for this
789 * Appliance.
790 *
791 * @param writeLock The current write lock.
792 * @param doc The xml document to fill.
793 * @param stack Structure for temporary private
794 * data shared with caller.
795 * @param strPath Path to the target OVF.
796 * instance for which to write XML.
797 * @param enFormat OVF format (0.9 or 1.0).
798 */
799void Appliance::i_buildXML(AutoWriteLockBase& writeLock,
800 xml::Document &doc,
801 XMLStack &stack,
802 const Utf8Str &strPath,
803 ovf::OVFVersion_T enFormat)
804{
805 xml::ElementNode *pelmRoot = doc.createRootElement("Envelope");
806
807 pelmRoot->setAttribute("ovf:version", enFormat == ovf::OVFVersion_2_0 ? "2.0"
808 : enFormat == ovf::OVFVersion_1_0 ? "1.0"
809 : "0.9");
810 pelmRoot->setAttribute("xml:lang", "en-US");
811
812 Utf8Str strNamespace;
813
814 if (enFormat == ovf::OVFVersion_0_9)
815 {
816 strNamespace = ovf::OVF09_URI_string;
817 }
818 else if (enFormat == ovf::OVFVersion_1_0)
819 {
820 strNamespace = ovf::OVF10_URI_string;
821 }
822 else
823 {
824 strNamespace = ovf::OVF20_URI_string;
825 }
826
827 pelmRoot->setAttribute("xmlns", strNamespace);
828 pelmRoot->setAttribute("xmlns:ovf", strNamespace);
829
830 // pelmRoot->setAttribute("xmlns:ovfstr", "http://schema.dmtf.org/ovf/strings/1");
831 pelmRoot->setAttribute("xmlns:rasd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData");
832 pelmRoot->setAttribute("xmlns:vssd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData");
833 pelmRoot->setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
834 pelmRoot->setAttribute("xmlns:vbox", "http://www.virtualbox.org/ovf/machine");
835 // pelmRoot->setAttribute("xsi:schemaLocation", "http://schemas.dmtf.org/ovf/envelope/1 ../ovf-envelope.xsd");
836
837 if (enFormat == ovf::OVFVersion_2_0)
838 {
839 pelmRoot->setAttribute("xmlns:epasd",
840 "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_EthernetPortAllocationSettingData.xsd");
841 pelmRoot->setAttribute("xmlns:sasd",
842 "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_StorageAllocationSettingData.xsd");
843 }
844
845 // <Envelope>/<References>
846 xml::ElementNode *pelmReferences = pelmRoot->createChild("References"); // 0.9 and 1.0
847
848 /* <Envelope>/<DiskSection>:
849 <DiskSection>
850 <Info>List of the virtual disks used in the package</Info>
851 <Disk ovf:capacity="4294967296" ovf:diskId="lamp" ovf:format="..." ovf:populatedSize="1924967692"/>
852 </DiskSection> */
853 xml::ElementNode *pelmDiskSection;
854 if (enFormat == ovf::OVFVersion_0_9)
855 {
856 // <Section xsi:type="ovf:DiskSection_Type">
857 pelmDiskSection = pelmRoot->createChild("Section");
858 pelmDiskSection->setAttribute("xsi:type", "ovf:DiskSection_Type");
859 }
860 else
861 pelmDiskSection = pelmRoot->createChild("DiskSection");
862
863 xml::ElementNode *pelmDiskSectionInfo = pelmDiskSection->createChild("Info");
864 pelmDiskSectionInfo->addContent("List of the virtual disks used in the package");
865
866 /* <Envelope>/<NetworkSection>:
867 <NetworkSection>
868 <Info>Logical networks used in the package</Info>
869 <Network ovf:name="VM Network">
870 <Description>The network that the LAMP Service will be available on</Description>
871 </Network>
872 </NetworkSection> */
873 xml::ElementNode *pelmNetworkSection;
874 if (enFormat == ovf::OVFVersion_0_9)
875 {
876 // <Section xsi:type="ovf:NetworkSection_Type">
877 pelmNetworkSection = pelmRoot->createChild("Section");
878 pelmNetworkSection->setAttribute("xsi:type", "ovf:NetworkSection_Type");
879 }
880 else
881 pelmNetworkSection = pelmRoot->createChild("NetworkSection");
882
883 xml::ElementNode *pelmNetworkSectionInfo = pelmNetworkSection->createChild("Info");
884 pelmNetworkSectionInfo->addContent("Logical networks used in the package");
885
886 // and here come the virtual systems:
887
888 // write a collection if we have more than one virtual system _and_ we're
889 // writing OVF 1.0; otherwise fail since ovftool can't import more than
890 // one machine, it seems
891 xml::ElementNode *pelmToAddVirtualSystemsTo;
892 if (m->virtualSystemDescriptions.size() > 1)
893 {
894 if (enFormat == ovf::OVFVersion_0_9)
895 throw setError(VBOX_E_FILE_ERROR,
896 tr("Cannot export more than one virtual system with OVF 0.9, use OVF 1.0"));
897
898 pelmToAddVirtualSystemsTo = pelmRoot->createChild("VirtualSystemCollection");
899 pelmToAddVirtualSystemsTo->setAttribute("ovf:name", "ExportedVirtualBoxMachines"); // whatever
900 }
901 else
902 pelmToAddVirtualSystemsTo = pelmRoot; // add virtual system directly under root element
903
904 // this list receives pointers to the XML elements in the machine XML which
905 // might have UUIDs that need fixing after we know the UUIDs of the exported images
906 std::list<xml::ElementNode*> llElementsWithUuidAttributes;
907
908 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
909 /* Iterate through all virtual systems of that appliance */
910 for (it = m->virtualSystemDescriptions.begin();
911 it != m->virtualSystemDescriptions.end();
912 ++it)
913 {
914 ComObjPtr<VirtualSystemDescription> vsdescThis = *it;
915 i_buildXMLForOneVirtualSystem(writeLock,
916 *pelmToAddVirtualSystemsTo,
917 &llElementsWithUuidAttributes,
918 vsdescThis,
919 enFormat,
920 stack); // disks and networks stack
921 }
922
923 // now, fill in the network section we set up empty above according
924 // to the networks we found with the hardware items
925 map<Utf8Str, bool>::const_iterator itN;
926 for (itN = stack.mapNetworks.begin();
927 itN != stack.mapNetworks.end();
928 ++itN)
929 {
930 const Utf8Str &strNetwork = itN->first;
931 xml::ElementNode *pelmNetwork = pelmNetworkSection->createChild("Network");
932 pelmNetwork->setAttribute("ovf:name", strNetwork.c_str());
933 pelmNetwork->createChild("Description")->addContent("Logical network used by this appliance.");
934 }
935
936 // Finally, write out the disk info
937 list<Utf8Str> diskList;
938 map<Utf8Str, const VirtualSystemDescriptionEntry*>::const_iterator itS;
939 uint32_t ulFile = 1;
940 for (itS = stack.mapDisks.begin();
941 itS != stack.mapDisks.end();
942 ++itS)
943 {
944 const Utf8Str &strDiskID = itS->first;
945 const VirtualSystemDescriptionEntry *pDiskEntry = itS->second;
946
947 // source path: where the VBox image is
948 const Utf8Str &strSrcFilePath = pDiskEntry->strVBoxCurrent;
949 Bstr bstrSrcFilePath(strSrcFilePath);
950
951 //skip empty Medium. There are no information to add into section <References> or <DiskSection>
952 if (strSrcFilePath.isEmpty() ||
953 pDiskEntry->skipIt == true)
954 continue;
955
956 // Do NOT check here whether the file exists. FindMedium will figure
957 // that out, and filesystem-based tests are simply wrong in the
958 // general case (think of iSCSI).
959
960 // We need some info from the source disks
961 ComPtr<IMedium> pSourceDisk;
962 //DeviceType_T deviceType = DeviceType_HardDisk;// by default
963
964 Log(("Finding source disk \"%ls\"\n", bstrSrcFilePath.raw()));
965
966 HRESULT rc;
967
968 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
969 {
970 rc = mVirtualBox->OpenMedium(bstrSrcFilePath.raw(),
971 DeviceType_HardDisk,
972 AccessMode_ReadWrite,
973 FALSE /* fForceNewUuid */,
974 pSourceDisk.asOutParam());
975 if (FAILED(rc))
976 throw rc;
977 }
978 else if (pDiskEntry->type == VirtualSystemDescriptionType_CDROM)//may be, this is CD/DVD
979 {
980 rc = mVirtualBox->OpenMedium(bstrSrcFilePath.raw(),
981 DeviceType_DVD,
982 AccessMode_ReadOnly,
983 FALSE,
984 pSourceDisk.asOutParam());
985 if (FAILED(rc))
986 throw rc;
987 }
988
989 Bstr uuidSource;
990 rc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
991 if (FAILED(rc)) throw rc;
992 Guid guidSource(uuidSource);
993
994 // output filename
995 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
996 // target path needs to be composed from where the output OVF is
997 Utf8Str strTargetFilePath(strPath);
998 strTargetFilePath.stripFilename();
999 strTargetFilePath.append("/");
1000 strTargetFilePath.append(strTargetFileNameOnly);
1001
1002 // We are always exporting to VMDK stream optimized for now
1003 //Bstr bstrSrcFormat = L"VMDK";//not used
1004
1005 diskList.push_back(strTargetFilePath);
1006
1007 LONG64 cbCapacity = 0; // size reported to guest
1008 rc = pSourceDisk->COMGETTER(LogicalSize)(&cbCapacity);
1009 if (FAILED(rc)) throw rc;
1010 /// @todo r=poetzsch: wrong it is reported in bytes ...
1011 // capacity is reported in megabytes, so...
1012 //cbCapacity *= _1M;
1013
1014 Guid guidTarget; /* Creates a new uniq number for the target disk. */
1015 guidTarget.create();
1016
1017 // now handle the XML for the disk:
1018 Utf8StrFmt strFileRef("file%RI32", ulFile++);
1019 // <File ovf:href="WindowsXpProfessional-disk1.vmdk" ovf:id="file1" ovf:size="1710381056"/>
1020 xml::ElementNode *pelmFile = pelmReferences->createChild("File");
1021 pelmFile->setAttribute("ovf:href", strTargetFileNameOnly);
1022 pelmFile->setAttribute("ovf:id", strFileRef);
1023 /// @todo the actual size is not available at this point of time,
1024 // cause the disk will be compressed. The 1.0 standard says this is
1025 // optional! 1.1 isn't fully clear if the "gzip" format is used.
1026 // Need to be checked. */
1027 // pelmFile->setAttribute("ovf:size", Utf8StrFmt("%RI64", cbFile).c_str());
1028
1029 // add disk to XML Disks section
1030 // <Disk ovf:capacity="8589934592" ovf:diskId="vmdisk1" ovf:fileRef="file1" ovf:format="..."/>
1031 xml::ElementNode *pelmDisk = pelmDiskSection->createChild("Disk");
1032 pelmDisk->setAttribute("ovf:capacity", Utf8StrFmt("%RI64", cbCapacity).c_str());
1033 pelmDisk->setAttribute("ovf:diskId", strDiskID);
1034 pelmDisk->setAttribute("ovf:fileRef", strFileRef);
1035
1036 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)//deviceType == DeviceType_HardDisk
1037 {
1038 pelmDisk->setAttribute("ovf:format",
1039 (enFormat == ovf::OVFVersion_0_9)
1040 ? "http://www.vmware.com/specifications/vmdk.html#sparse" // must be sparse or ovftool ch
1041 : "http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized"
1042 // correct string as communicated to us by VMware (public bug #6612)
1043 );
1044 }
1045 else //pDiskEntry->type == VirtualSystemDescriptionType_CDROM, deviceType == DeviceType_DVD
1046 {
1047 pelmDisk->setAttribute("ovf:format",
1048 "http://www.ecma-international.org/publications/standards/Ecma-119.htm"
1049 );
1050 }
1051
1052 // add the UUID of the newly target image to the OVF disk element, but in the
1053 // vbox: namespace since it's not part of the standard
1054 pelmDisk->setAttribute("vbox:uuid", Utf8StrFmt("%RTuuid", guidTarget.raw()).c_str());
1055
1056 // now, we might have other XML elements from vbox:Machine pointing to this image,
1057 // but those would refer to the UUID of the _source_ image (which we created the
1058 // export image from); those UUIDs need to be fixed to the export image
1059 Utf8Str strGuidSourceCurly = guidSource.toStringCurly();
1060 for (std::list<xml::ElementNode*>::iterator eit = llElementsWithUuidAttributes.begin();
1061 eit != llElementsWithUuidAttributes.end();
1062 ++eit)
1063 {
1064 xml::ElementNode *pelmImage = *eit;
1065 Utf8Str strUUID;
1066 pelmImage->getAttributeValue("uuid", strUUID);
1067 if (strUUID == strGuidSourceCurly)
1068 // overwrite existing uuid attribute
1069 pelmImage->setAttribute("uuid", guidTarget.toStringCurly());
1070 }
1071 }
1072}
1073
1074/**
1075 * Called from Appliance::i_buildXML() for each virtual system (machine) that
1076 * needs XML written out.
1077 *
1078 * @param writeLock The current write lock.
1079 * @param elmToAddVirtualSystemsTo XML element to append elements to.
1080 * @param pllElementsWithUuidAttributes out: list of XML elements produced here
1081 * with UUID attributes for quick
1082 * fixing by caller later
1083 * @param vsdescThis The IVirtualSystemDescription
1084 * instance for which to write XML.
1085 * @param enFormat OVF format (0.9 or 1.0).
1086 * @param stack Structure for temporary private
1087 * data shared with caller.
1088 */
1089void Appliance::i_buildXMLForOneVirtualSystem(AutoWriteLockBase& writeLock,
1090 xml::ElementNode &elmToAddVirtualSystemsTo,
1091 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes,
1092 ComObjPtr<VirtualSystemDescription> &vsdescThis,
1093 ovf::OVFVersion_T enFormat,
1094 XMLStack &stack)
1095{
1096 LogFlowFunc(("ENTER appliance %p\n", this));
1097
1098 xml::ElementNode *pelmVirtualSystem;
1099 if (enFormat == ovf::OVFVersion_0_9)
1100 {
1101 // <Section xsi:type="ovf:NetworkSection_Type">
1102 pelmVirtualSystem = elmToAddVirtualSystemsTo.createChild("Content");
1103 pelmVirtualSystem->setAttribute("xsi:type", "ovf:VirtualSystem_Type");
1104 }
1105 else
1106 pelmVirtualSystem = elmToAddVirtualSystemsTo.createChild("VirtualSystem");
1107
1108 /*xml::ElementNode *pelmVirtualSystemInfo =*/ pelmVirtualSystem->createChild("Info")->addContent("A virtual machine");
1109
1110 std::list<VirtualSystemDescriptionEntry*> llName = vsdescThis->i_findByType(VirtualSystemDescriptionType_Name);
1111 if (llName.empty())
1112 throw setError(VBOX_E_NOT_SUPPORTED, tr("Missing VM name"));
1113 Utf8Str &strVMName = llName.back()->strVBoxCurrent;
1114 pelmVirtualSystem->setAttribute("ovf:id", strVMName);
1115
1116 // product info
1117 std::list<VirtualSystemDescriptionEntry*> llProduct = vsdescThis->i_findByType(VirtualSystemDescriptionType_Product);
1118 std::list<VirtualSystemDescriptionEntry*> llProductUrl = vsdescThis->i_findByType(VirtualSystemDescriptionType_ProductUrl);
1119 std::list<VirtualSystemDescriptionEntry*> llVendor = vsdescThis->i_findByType(VirtualSystemDescriptionType_Vendor);
1120 std::list<VirtualSystemDescriptionEntry*> llVendorUrl = vsdescThis->i_findByType(VirtualSystemDescriptionType_VendorUrl);
1121 std::list<VirtualSystemDescriptionEntry*> llVersion = vsdescThis->i_findByType(VirtualSystemDescriptionType_Version);
1122 bool fProduct = llProduct.size() && !llProduct.back()->strVBoxCurrent.isEmpty();
1123 bool fProductUrl = llProductUrl.size() && !llProductUrl.back()->strVBoxCurrent.isEmpty();
1124 bool fVendor = llVendor.size() && !llVendor.back()->strVBoxCurrent.isEmpty();
1125 bool fVendorUrl = llVendorUrl.size() && !llVendorUrl.back()->strVBoxCurrent.isEmpty();
1126 bool fVersion = llVersion.size() && !llVersion.back()->strVBoxCurrent.isEmpty();
1127 if (fProduct || fProductUrl || fVendor || fVendorUrl || fVersion)
1128 {
1129 /* <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
1130 <Info>Meta-information about the installed software</Info>
1131 <Product>VAtest</Product>
1132 <Vendor>SUN Microsystems</Vendor>
1133 <Version>10.0</Version>
1134 <ProductUrl>http://blogs.sun.com/VirtualGuru</ProductUrl>
1135 <VendorUrl>http://www.sun.com</VendorUrl>
1136 </Section> */
1137 xml::ElementNode *pelmAnnotationSection;
1138 if (enFormat == ovf::OVFVersion_0_9)
1139 {
1140 // <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
1141 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
1142 pelmAnnotationSection->setAttribute("xsi:type", "ovf:ProductSection_Type");
1143 }
1144 else
1145 pelmAnnotationSection = pelmVirtualSystem->createChild("ProductSection");
1146
1147 pelmAnnotationSection->createChild("Info")->addContent("Meta-information about the installed software");
1148 if (fProduct)
1149 pelmAnnotationSection->createChild("Product")->addContent(llProduct.back()->strVBoxCurrent);
1150 if (fVendor)
1151 pelmAnnotationSection->createChild("Vendor")->addContent(llVendor.back()->strVBoxCurrent);
1152 if (fVersion)
1153 pelmAnnotationSection->createChild("Version")->addContent(llVersion.back()->strVBoxCurrent);
1154 if (fProductUrl)
1155 pelmAnnotationSection->createChild("ProductUrl")->addContent(llProductUrl.back()->strVBoxCurrent);
1156 if (fVendorUrl)
1157 pelmAnnotationSection->createChild("VendorUrl")->addContent(llVendorUrl.back()->strVBoxCurrent);
1158 }
1159
1160 // description
1161 std::list<VirtualSystemDescriptionEntry*> llDescription = vsdescThis->i_findByType(VirtualSystemDescriptionType_Description);
1162 if (llDescription.size() &&
1163 !llDescription.back()->strVBoxCurrent.isEmpty())
1164 {
1165 /* <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
1166 <Info>A human-readable annotation</Info>
1167 <Annotation>Plan 9</Annotation>
1168 </Section> */
1169 xml::ElementNode *pelmAnnotationSection;
1170 if (enFormat == ovf::OVFVersion_0_9)
1171 {
1172 // <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
1173 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
1174 pelmAnnotationSection->setAttribute("xsi:type", "ovf:AnnotationSection_Type");
1175 }
1176 else
1177 pelmAnnotationSection = pelmVirtualSystem->createChild("AnnotationSection");
1178
1179 pelmAnnotationSection->createChild("Info")->addContent("A human-readable annotation");
1180 pelmAnnotationSection->createChild("Annotation")->addContent(llDescription.back()->strVBoxCurrent);
1181 }
1182
1183 // license
1184 std::list<VirtualSystemDescriptionEntry*> llLicense = vsdescThis->i_findByType(VirtualSystemDescriptionType_License);
1185 if (llLicense.size() &&
1186 !llLicense.back()->strVBoxCurrent.isEmpty())
1187 {
1188 /* <EulaSection>
1189 <Info ovf:msgid="6">License agreement for the Virtual System.</Info>
1190 <License ovf:msgid="1">License terms can go in here.</License>
1191 </EulaSection> */
1192 xml::ElementNode *pelmEulaSection;
1193 if (enFormat == ovf::OVFVersion_0_9)
1194 {
1195 pelmEulaSection = pelmVirtualSystem->createChild("Section");
1196 pelmEulaSection->setAttribute("xsi:type", "ovf:EulaSection_Type");
1197 }
1198 else
1199 pelmEulaSection = pelmVirtualSystem->createChild("EulaSection");
1200
1201 pelmEulaSection->createChild("Info")->addContent("License agreement for the virtual system");
1202 pelmEulaSection->createChild("License")->addContent(llLicense.back()->strVBoxCurrent);
1203 }
1204
1205 // operating system
1206 std::list<VirtualSystemDescriptionEntry*> llOS = vsdescThis->i_findByType(VirtualSystemDescriptionType_OS);
1207 if (llOS.empty())
1208 throw setError(VBOX_E_NOT_SUPPORTED, tr("Missing OS type"));
1209 /* <OperatingSystemSection ovf:id="82">
1210 <Info>Guest Operating System</Info>
1211 <Description>Linux 2.6.x</Description>
1212 </OperatingSystemSection> */
1213 VirtualSystemDescriptionEntry *pvsdeOS = llOS.back();
1214 xml::ElementNode *pelmOperatingSystemSection;
1215 if (enFormat == ovf::OVFVersion_0_9)
1216 {
1217 pelmOperatingSystemSection = pelmVirtualSystem->createChild("Section");
1218 pelmOperatingSystemSection->setAttribute("xsi:type", "ovf:OperatingSystemSection_Type");
1219 }
1220 else
1221 pelmOperatingSystemSection = pelmVirtualSystem->createChild("OperatingSystemSection");
1222
1223 pelmOperatingSystemSection->setAttribute("ovf:id", pvsdeOS->strOvf);
1224 pelmOperatingSystemSection->createChild("Info")->addContent("The kind of installed guest operating system");
1225 Utf8Str strOSDesc;
1226 convertCIMOSType2VBoxOSType(strOSDesc, (ovf::CIMOSType_T)pvsdeOS->strOvf.toInt32(), "");
1227 pelmOperatingSystemSection->createChild("Description")->addContent(strOSDesc);
1228 // add the VirtualBox ostype in a custom tag in a different namespace
1229 xml::ElementNode *pelmVBoxOSType = pelmOperatingSystemSection->createChild("vbox:OSType");
1230 pelmVBoxOSType->setAttribute("ovf:required", "false");
1231 pelmVBoxOSType->addContent(pvsdeOS->strVBoxCurrent);
1232
1233 // <VirtualHardwareSection ovf:id="hw1" ovf:transport="iso">
1234 xml::ElementNode *pelmVirtualHardwareSection;
1235 if (enFormat == ovf::OVFVersion_0_9)
1236 {
1237 // <Section xsi:type="ovf:VirtualHardwareSection_Type">
1238 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("Section");
1239 pelmVirtualHardwareSection->setAttribute("xsi:type", "ovf:VirtualHardwareSection_Type");
1240 }
1241 else
1242 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("VirtualHardwareSection");
1243
1244 pelmVirtualHardwareSection->createChild("Info")->addContent("Virtual hardware requirements for a virtual machine");
1245
1246 /* <System>
1247 <vssd:Description>Description of the virtual hardware section.</vssd:Description>
1248 <vssd:ElementName>vmware</vssd:ElementName>
1249 <vssd:InstanceID>1</vssd:InstanceID>
1250 <vssd:VirtualSystemIdentifier>MyLampService</vssd:VirtualSystemIdentifier>
1251 <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
1252 </System> */
1253 xml::ElementNode *pelmSystem = pelmVirtualHardwareSection->createChild("System");
1254
1255 pelmSystem->createChild("vssd:ElementName")->addContent("Virtual Hardware Family"); // required OVF 1.0
1256
1257 // <vssd:InstanceId>0</vssd:InstanceId>
1258 if (enFormat == ovf::OVFVersion_0_9)
1259 pelmSystem->createChild("vssd:InstanceId")->addContent("0");
1260 else // capitalization changed...
1261 pelmSystem->createChild("vssd:InstanceID")->addContent("0");
1262
1263 // <vssd:VirtualSystemIdentifier>VAtest</vssd:VirtualSystemIdentifier>
1264 pelmSystem->createChild("vssd:VirtualSystemIdentifier")->addContent(strVMName);
1265 // <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
1266 const char *pcszHardware = "virtualbox-2.2";
1267 if (enFormat == ovf::OVFVersion_0_9)
1268 // pretend to be vmware compatible then
1269 pcszHardware = "vmx-6";
1270 pelmSystem->createChild("vssd:VirtualSystemType")->addContent(pcszHardware);
1271
1272 // loop thru all description entries twice; once to write out all
1273 // devices _except_ disk images, and a second time to assign the
1274 // disk images; this is because disk images need to reference
1275 // IDE controllers, and we can't know their instance IDs without
1276 // assigning them first
1277
1278 uint32_t idIDEPrimaryController = 0;
1279 int32_t lIDEPrimaryControllerIndex = 0;
1280 uint32_t idIDESecondaryController = 0;
1281 int32_t lIDESecondaryControllerIndex = 0;
1282 uint32_t idSATAController = 0;
1283 int32_t lSATAControllerIndex = 0;
1284 uint32_t idSCSIController = 0;
1285 int32_t lSCSIControllerIndex = 0;
1286
1287 uint32_t ulInstanceID = 1;
1288
1289 uint32_t cDVDs = 0;
1290
1291 for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
1292 {
1293 int32_t lIndexThis = 0;
1294 vector<VirtualSystemDescriptionEntry>::const_iterator itD;
1295 for (itD = vsdescThis->m->maDescriptions.begin();
1296 itD != vsdescThis->m->maDescriptions.end();
1297 ++itD, ++lIndexThis)
1298 {
1299 const VirtualSystemDescriptionEntry &desc = *itD;
1300
1301 LogFlowFunc(("Loop %u: handling description entry ulIndex=%u, type=%s, strRef=%s, strOvf=%s, strVBox=%s, strExtraConfig=%s\n",
1302 uLoop,
1303 desc.ulIndex,
1304 ( desc.type == VirtualSystemDescriptionType_HardDiskControllerIDE ? "HardDiskControllerIDE"
1305 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSATA ? "HardDiskControllerSATA"
1306 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSCSI ? "HardDiskControllerSCSI"
1307 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSAS ? "HardDiskControllerSAS"
1308 : desc.type == VirtualSystemDescriptionType_HardDiskImage ? "HardDiskImage"
1309 : Utf8StrFmt("%d", desc.type).c_str()),
1310 desc.strRef.c_str(),
1311 desc.strOvf.c_str(),
1312 desc.strVBoxCurrent.c_str(),
1313 desc.strExtraConfigCurrent.c_str()));
1314
1315 ovf::ResourceType_T type = (ovf::ResourceType_T)0; // if this becomes != 0 then we do stuff
1316 Utf8Str strResourceSubType;
1317
1318 Utf8Str strDescription; // results in <rasd:Description>...</rasd:Description> block
1319 Utf8Str strCaption; // results in <rasd:Caption>...</rasd:Caption> block
1320
1321 uint32_t ulParent = 0;
1322
1323 int32_t lVirtualQuantity = -1;
1324 Utf8Str strAllocationUnits;
1325
1326 int32_t lAddress = -1;
1327 int32_t lBusNumber = -1;
1328 int32_t lAddressOnParent = -1;
1329
1330 int32_t lAutomaticAllocation = -1; // 0 means "false", 1 means "true"
1331 Utf8Str strConnection; // results in <rasd:Connection>...</rasd:Connection> block
1332 Utf8Str strHostResource;
1333
1334 uint64_t uTemp;
1335
1336 ovf::VirtualHardwareItem vhi;
1337 ovf::StorageItem si;
1338 ovf::EthernetPortItem epi;
1339
1340 switch (desc.type)
1341 {
1342 case VirtualSystemDescriptionType_CPU:
1343 /* <Item>
1344 <rasd:Caption>1 virtual CPU</rasd:Caption>
1345 <rasd:Description>Number of virtual CPUs</rasd:Description>
1346 <rasd:ElementName>virtual CPU</rasd:ElementName>
1347 <rasd:InstanceID>1</rasd:InstanceID>
1348 <rasd:ResourceType>3</rasd:ResourceType>
1349 <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
1350 </Item> */
1351 if (uLoop == 1)
1352 {
1353 strDescription = "Number of virtual CPUs";
1354 type = ovf::ResourceType_Processor; // 3
1355 desc.strVBoxCurrent.toInt(uTemp);
1356 lVirtualQuantity = (int32_t)uTemp;
1357 strCaption = Utf8StrFmt("%d virtual CPU", lVirtualQuantity); // without this ovftool
1358 // won't eat the item
1359 }
1360 break;
1361
1362 case VirtualSystemDescriptionType_Memory:
1363 /* <Item>
1364 <rasd:AllocationUnits>MegaBytes</rasd:AllocationUnits>
1365 <rasd:Caption>256 MB of memory</rasd:Caption>
1366 <rasd:Description>Memory Size</rasd:Description>
1367 <rasd:ElementName>Memory</rasd:ElementName>
1368 <rasd:InstanceID>2</rasd:InstanceID>
1369 <rasd:ResourceType>4</rasd:ResourceType>
1370 <rasd:VirtualQuantity>256</rasd:VirtualQuantity>
1371 </Item> */
1372 if (uLoop == 1)
1373 {
1374 strDescription = "Memory Size";
1375 type = ovf::ResourceType_Memory; // 4
1376 desc.strVBoxCurrent.toInt(uTemp);
1377 lVirtualQuantity = (int32_t)(uTemp / _1M);
1378 strAllocationUnits = "MegaBytes";
1379 strCaption = Utf8StrFmt("%d MB of memory", lVirtualQuantity); // without this ovftool
1380 // won't eat the item
1381 }
1382 break;
1383
1384 case VirtualSystemDescriptionType_HardDiskControllerIDE:
1385 /* <Item>
1386 <rasd:Caption>ideController1</rasd:Caption>
1387 <rasd:Description>IDE Controller</rasd:Description>
1388 <rasd:InstanceId>5</rasd:InstanceId>
1389 <rasd:ResourceType>5</rasd:ResourceType>
1390 <rasd:Address>1</rasd:Address>
1391 <rasd:BusNumber>1</rasd:BusNumber>
1392 </Item> */
1393 if (uLoop == 1)
1394 {
1395 strDescription = "IDE Controller";
1396 type = ovf::ResourceType_IDEController; // 5
1397 strResourceSubType = desc.strVBoxCurrent;
1398
1399 if (!lIDEPrimaryControllerIndex)
1400 {
1401 // first IDE controller:
1402 strCaption = "ideController0";
1403 lAddress = 0;
1404 lBusNumber = 0;
1405 // remember this ID
1406 idIDEPrimaryController = ulInstanceID;
1407 lIDEPrimaryControllerIndex = lIndexThis;
1408 }
1409 else
1410 {
1411 // second IDE controller:
1412 strCaption = "ideController1";
1413 lAddress = 1;
1414 lBusNumber = 1;
1415 // remember this ID
1416 idIDESecondaryController = ulInstanceID;
1417 lIDESecondaryControllerIndex = lIndexThis;
1418 }
1419 }
1420 break;
1421
1422 case VirtualSystemDescriptionType_HardDiskControllerSATA:
1423 /* <Item>
1424 <rasd:Caption>sataController0</rasd:Caption>
1425 <rasd:Description>SATA Controller</rasd:Description>
1426 <rasd:InstanceId>4</rasd:InstanceId>
1427 <rasd:ResourceType>20</rasd:ResourceType>
1428 <rasd:ResourceSubType>ahci</rasd:ResourceSubType>
1429 <rasd:Address>0</rasd:Address>
1430 <rasd:BusNumber>0</rasd:BusNumber>
1431 </Item>
1432 */
1433 if (uLoop == 1)
1434 {
1435 strDescription = "SATA Controller";
1436 strCaption = "sataController0";
1437 type = ovf::ResourceType_OtherStorageDevice; // 20
1438 // it seems that OVFTool always writes these two, and since we can only
1439 // have one SATA controller, we'll use this as well
1440 lAddress = 0;
1441 lBusNumber = 0;
1442
1443 if ( desc.strVBoxCurrent.isEmpty() // AHCI is the default in VirtualBox
1444 || (!desc.strVBoxCurrent.compare("ahci", Utf8Str::CaseInsensitive))
1445 )
1446 strResourceSubType = "AHCI";
1447 else
1448 throw setError(VBOX_E_NOT_SUPPORTED,
1449 tr("Invalid config string \"%s\" in SATA controller"), desc.strVBoxCurrent.c_str());
1450
1451 // remember this ID
1452 idSATAController = ulInstanceID;
1453 lSATAControllerIndex = lIndexThis;
1454 }
1455 break;
1456
1457 case VirtualSystemDescriptionType_HardDiskControllerSCSI:
1458 case VirtualSystemDescriptionType_HardDiskControllerSAS:
1459 /* <Item>
1460 <rasd:Caption>scsiController0</rasd:Caption>
1461 <rasd:Description>SCSI Controller</rasd:Description>
1462 <rasd:InstanceId>4</rasd:InstanceId>
1463 <rasd:ResourceType>6</rasd:ResourceType>
1464 <rasd:ResourceSubType>buslogic</rasd:ResourceSubType>
1465 <rasd:Address>0</rasd:Address>
1466 <rasd:BusNumber>0</rasd:BusNumber>
1467 </Item>
1468 */
1469 if (uLoop == 1)
1470 {
1471 strDescription = "SCSI Controller";
1472 strCaption = "scsiController0";
1473 type = ovf::ResourceType_ParallelSCSIHBA; // 6
1474 // it seems that OVFTool always writes these two, and since we can only
1475 // have one SATA controller, we'll use this as well
1476 lAddress = 0;
1477 lBusNumber = 0;
1478
1479 if ( desc.strVBoxCurrent.isEmpty() // LsiLogic is the default in VirtualBox
1480 || (!desc.strVBoxCurrent.compare("lsilogic", Utf8Str::CaseInsensitive))
1481 )
1482 strResourceSubType = "lsilogic";
1483 else if (!desc.strVBoxCurrent.compare("buslogic", Utf8Str::CaseInsensitive))
1484 strResourceSubType = "buslogic";
1485 else if (!desc.strVBoxCurrent.compare("lsilogicsas", Utf8Str::CaseInsensitive))
1486 strResourceSubType = "lsilogicsas";
1487 else
1488 throw setError(VBOX_E_NOT_SUPPORTED,
1489 tr("Invalid config string \"%s\" in SCSI/SAS controller"),
1490 desc.strVBoxCurrent.c_str());
1491
1492 // remember this ID
1493 idSCSIController = ulInstanceID;
1494 lSCSIControllerIndex = lIndexThis;
1495 }
1496 break;
1497
1498 case VirtualSystemDescriptionType_HardDiskImage:
1499 /* <Item>
1500 <rasd:Caption>disk1</rasd:Caption>
1501 <rasd:InstanceId>8</rasd:InstanceId>
1502 <rasd:ResourceType>17</rasd:ResourceType>
1503 <rasd:HostResource>/disk/vmdisk1</rasd:HostResource>
1504 <rasd:Parent>4</rasd:Parent>
1505 <rasd:AddressOnParent>0</rasd:AddressOnParent>
1506 </Item> */
1507 if (uLoop == 2)
1508 {
1509 uint32_t cDisks = (uint32_t)stack.mapDisks.size();
1510 Utf8Str strDiskID = Utf8StrFmt("vmdisk%RI32", ++cDisks);
1511
1512 strDescription = "Disk Image";
1513 strCaption = Utf8StrFmt("disk%RI32", cDisks); // this is not used for anything else
1514 type = ovf::ResourceType_HardDisk; // 17
1515
1516 // the following references the "<Disks>" XML block
1517 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
1518
1519 // controller=<index>;channel=<c>
1520 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1521 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1522 int32_t lControllerIndex = -1;
1523 if (pos1 != Utf8Str::npos)
1524 {
1525 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1526 if (lControllerIndex == lIDEPrimaryControllerIndex)
1527 ulParent = idIDEPrimaryController;
1528 else if (lControllerIndex == lIDESecondaryControllerIndex)
1529 ulParent = idIDESecondaryController;
1530 else if (lControllerIndex == lSCSIControllerIndex)
1531 ulParent = idSCSIController;
1532 else if (lControllerIndex == lSATAControllerIndex)
1533 ulParent = idSATAController;
1534 }
1535 if (pos2 != Utf8Str::npos)
1536 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1537
1538 LogFlowFunc(("HardDiskImage details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1539 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex, lIDESecondaryControllerIndex,
1540 ulParent, lAddressOnParent));
1541
1542 if ( !ulParent
1543 || lAddressOnParent == -1
1544 )
1545 throw setError(VBOX_E_NOT_SUPPORTED,
1546 tr("Missing or bad extra config string in hard disk image: \"%s\""),
1547 desc.strExtraConfigCurrent.c_str());
1548
1549 stack.mapDisks[strDiskID] = &desc;
1550 }
1551 break;
1552
1553 case VirtualSystemDescriptionType_Floppy:
1554 if (uLoop == 1)
1555 {
1556 strDescription = "Floppy Drive";
1557 strCaption = "floppy0"; // this is what OVFTool writes
1558 type = ovf::ResourceType_FloppyDrive; // 14
1559 lAutomaticAllocation = 0;
1560 lAddressOnParent = 0; // this is what OVFTool writes
1561 }
1562 break;
1563
1564 case VirtualSystemDescriptionType_CDROM:
1565 /* <Item>
1566 <rasd:Caption>cdrom1</rasd:Caption>
1567 <rasd:InstanceId>8</rasd:InstanceId>
1568 <rasd:ResourceType>15</rasd:ResourceType>
1569 <rasd:HostResource>/disk/cdrom1</rasd:HostResource>
1570 <rasd:Parent>4</rasd:Parent>
1571 <rasd:AddressOnParent>0</rasd:AddressOnParent>
1572 </Item> */
1573 if (uLoop == 2)
1574 {
1575 //uint32_t cDisks = stack.mapDisks.size();
1576 Utf8Str strDiskID = Utf8StrFmt("iso%RI32", ++cDVDs);
1577
1578 strDescription = "CD-ROM Drive";
1579 strCaption = Utf8StrFmt("cdrom%RI32", cDVDs); // OVFTool starts with 1
1580 type = ovf::ResourceType_CDDrive; // 15
1581 lAutomaticAllocation = 1;
1582
1583 //skip empty Medium. There are no information to add into section <References> or <DiskSection>
1584 if (desc.strVBoxCurrent.isNotEmpty() &&
1585 desc.skipIt == false)
1586 {
1587 // the following references the "<Disks>" XML block
1588 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
1589 }
1590
1591 // controller=<index>;channel=<c>
1592 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1593 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1594 int32_t lControllerIndex = -1;
1595 if (pos1 != Utf8Str::npos)
1596 {
1597 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1598 if (lControllerIndex == lIDEPrimaryControllerIndex)
1599 ulParent = idIDEPrimaryController;
1600 else if (lControllerIndex == lIDESecondaryControllerIndex)
1601 ulParent = idIDESecondaryController;
1602 else if (lControllerIndex == lSCSIControllerIndex)
1603 ulParent = idSCSIController;
1604 else if (lControllerIndex == lSATAControllerIndex)
1605 ulParent = idSATAController;
1606 }
1607 if (pos2 != Utf8Str::npos)
1608 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1609
1610 LogFlowFunc(("DVD drive details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1611 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex,
1612 lIDESecondaryControllerIndex, ulParent, lAddressOnParent));
1613
1614 if ( !ulParent
1615 || lAddressOnParent == -1
1616 )
1617 throw setError(VBOX_E_NOT_SUPPORTED,
1618 tr("Missing or bad extra config string in DVD drive medium: \"%s\""),
1619 desc.strExtraConfigCurrent.c_str());
1620
1621 stack.mapDisks[strDiskID] = &desc;
1622 // there is no DVD drive map to update because it is
1623 // handled completely with this entry.
1624 }
1625 break;
1626
1627 case VirtualSystemDescriptionType_NetworkAdapter:
1628 /* <Item>
1629 <rasd:AutomaticAllocation>true</rasd:AutomaticAllocation>
1630 <rasd:Caption>Ethernet adapter on 'VM Network'</rasd:Caption>
1631 <rasd:Connection>VM Network</rasd:Connection>
1632 <rasd:ElementName>VM network</rasd:ElementName>
1633 <rasd:InstanceID>3</rasd:InstanceID>
1634 <rasd:ResourceType>10</rasd:ResourceType>
1635 </Item> */
1636 if (uLoop == 2)
1637 {
1638 lAutomaticAllocation = 1;
1639 strCaption = Utf8StrFmt("Ethernet adapter on '%s'", desc.strOvf.c_str());
1640 type = ovf::ResourceType_EthernetAdapter; // 10
1641 /* Set the hardware type to something useful.
1642 * To be compatible with vmware & others we set
1643 * PCNet32 for our PCNet types & E1000 for the
1644 * E1000 cards. */
1645 switch (desc.strVBoxCurrent.toInt32())
1646 {
1647 case NetworkAdapterType_Am79C970A:
1648 case NetworkAdapterType_Am79C973: strResourceSubType = "PCNet32"; break;
1649#ifdef VBOX_WITH_E1000
1650 case NetworkAdapterType_I82540EM:
1651 case NetworkAdapterType_I82545EM:
1652 case NetworkAdapterType_I82543GC: strResourceSubType = "E1000"; break;
1653#endif /* VBOX_WITH_E1000 */
1654 }
1655 strConnection = desc.strOvf;
1656
1657 stack.mapNetworks[desc.strOvf] = true;
1658 }
1659 break;
1660
1661 case VirtualSystemDescriptionType_USBController:
1662 /* <Item ovf:required="false">
1663 <rasd:Caption>usb</rasd:Caption>
1664 <rasd:Description>USB Controller</rasd:Description>
1665 <rasd:InstanceId>3</rasd:InstanceId>
1666 <rasd:ResourceType>23</rasd:ResourceType>
1667 <rasd:Address>0</rasd:Address>
1668 <rasd:BusNumber>0</rasd:BusNumber>
1669 </Item> */
1670 if (uLoop == 1)
1671 {
1672 strDescription = "USB Controller";
1673 strCaption = "usb";
1674 type = ovf::ResourceType_USBController; // 23
1675 lAddress = 0; // this is what OVFTool writes
1676 lBusNumber = 0; // this is what OVFTool writes
1677 }
1678 break;
1679
1680 case VirtualSystemDescriptionType_SoundCard:
1681 /* <Item ovf:required="false">
1682 <rasd:Caption>sound</rasd:Caption>
1683 <rasd:Description>Sound Card</rasd:Description>
1684 <rasd:InstanceId>10</rasd:InstanceId>
1685 <rasd:ResourceType>35</rasd:ResourceType>
1686 <rasd:ResourceSubType>ensoniq1371</rasd:ResourceSubType>
1687 <rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
1688 <rasd:AddressOnParent>3</rasd:AddressOnParent>
1689 </Item> */
1690 if (uLoop == 1)
1691 {
1692 strDescription = "Sound Card";
1693 strCaption = "sound";
1694 type = ovf::ResourceType_SoundCard; // 35
1695 strResourceSubType = desc.strOvf; // e.g. ensoniq1371
1696 lAutomaticAllocation = 0;
1697 lAddressOnParent = 3; // what gives? this is what OVFTool writes
1698 }
1699 break;
1700
1701 default: break; /* Shut up MSC. */
1702 }
1703
1704 if (type)
1705 {
1706 xml::ElementNode *pItem;
1707 xml::ElementNode *pItemHelper;
1708 RTCString itemElement;
1709 RTCString itemElementHelper;
1710
1711 if (enFormat == ovf::OVFVersion_2_0)
1712 {
1713 if(uLoop == 2)
1714 {
1715 if (desc.type == VirtualSystemDescriptionType_NetworkAdapter)
1716 {
1717 itemElement = "epasd:";
1718 pItem = pelmVirtualHardwareSection->createChild("EthernetPortItem");
1719 }
1720 else if (desc.type == VirtualSystemDescriptionType_CDROM ||
1721 desc.type == VirtualSystemDescriptionType_HardDiskImage)
1722 {
1723 itemElement = "sasd:";
1724 pItem = pelmVirtualHardwareSection->createChild("StorageItem");
1725 }
1726 else
1727 pItem = NULL;
1728 }
1729 else
1730 {
1731 itemElement = "rasd:";
1732 pItem = pelmVirtualHardwareSection->createChild("Item");
1733 }
1734 }
1735 else
1736 {
1737 itemElement = "rasd:";
1738 pItem = pelmVirtualHardwareSection->createChild("Item");
1739 }
1740
1741 // NOTE: DO NOT CHANGE THE ORDER of these items! The OVF standards prescribes that
1742 // the elements from the rasd: namespace must be sorted by letter, and VMware
1743 // actually requires this as well (see public bug #6612)
1744
1745 if (lAddress != -1)
1746 {
1747 //pItem->createChild("rasd:Address")->addContent(Utf8StrFmt("%d", lAddress));
1748 itemElementHelper = itemElement;
1749 pItemHelper = pItem->createChild(itemElementHelper.append("Address").c_str());
1750 pItemHelper->addContent(Utf8StrFmt("%d", lAddress));
1751 }
1752
1753 if (lAddressOnParent != -1)
1754 {
1755 //pItem->createChild("rasd:AddressOnParent")->addContent(Utf8StrFmt("%d", lAddressOnParent));
1756 itemElementHelper = itemElement;
1757 pItemHelper = pItem->createChild(itemElementHelper.append("AddressOnParent").c_str());
1758 pItemHelper->addContent(Utf8StrFmt("%d", lAddressOnParent));
1759 }
1760
1761 if (!strAllocationUnits.isEmpty())
1762 {
1763 //pItem->createChild("rasd:AllocationUnits")->addContent(strAllocationUnits);
1764 itemElementHelper = itemElement;
1765 pItemHelper = pItem->createChild(itemElementHelper.append("AllocationUnits").c_str());
1766 pItemHelper->addContent(strAllocationUnits);
1767 }
1768
1769 if (lAutomaticAllocation != -1)
1770 {
1771 //pItem->createChild("rasd:AutomaticAllocation")->addContent( (lAutomaticAllocation) ? "true" : "false" );
1772 itemElementHelper = itemElement;
1773 pItemHelper = pItem->createChild(itemElementHelper.append("AutomaticAllocation").c_str());
1774 pItemHelper->addContent((lAutomaticAllocation) ? "true" : "false" );
1775 }
1776
1777 if (lBusNumber != -1)
1778 {
1779 if (enFormat == ovf::OVFVersion_0_9)
1780 {
1781 // BusNumber is invalid OVF 1.0 so only write it in 0.9 mode for OVFTool
1782 //pItem->createChild("rasd:BusNumber")->addContent(Utf8StrFmt("%d", lBusNumber));
1783 itemElementHelper = itemElement;
1784 pItemHelper = pItem->createChild(itemElementHelper.append("BusNumber").c_str());
1785 pItemHelper->addContent(Utf8StrFmt("%d", lBusNumber));
1786 }
1787 }
1788
1789 if (!strCaption.isEmpty())
1790 {
1791 //pItem->createChild("rasd:Caption")->addContent(strCaption);
1792 itemElementHelper = itemElement;
1793 pItemHelper = pItem->createChild(itemElementHelper.append("Caption").c_str());
1794 pItemHelper->addContent(strCaption);
1795 }
1796
1797 if (!strConnection.isEmpty())
1798 {
1799 //pItem->createChild("rasd:Connection")->addContent(strConnection);
1800 itemElementHelper = itemElement;
1801 pItemHelper = pItem->createChild(itemElementHelper.append("Connection").c_str());
1802 pItemHelper->addContent(strConnection);
1803 }
1804
1805 if (!strDescription.isEmpty())
1806 {
1807 //pItem->createChild("rasd:Description")->addContent(strDescription);
1808 itemElementHelper = itemElement;
1809 pItemHelper = pItem->createChild(itemElementHelper.append("Description").c_str());
1810 pItemHelper->addContent(strDescription);
1811 }
1812
1813 if (!strCaption.isEmpty())
1814 {
1815 if (enFormat == ovf::OVFVersion_1_0)
1816 {
1817 //pItem->createChild("rasd:ElementName")->addContent(strCaption);
1818 itemElementHelper = itemElement;
1819 pItemHelper = pItem->createChild(itemElementHelper.append("ElementName").c_str());
1820 pItemHelper->addContent(strCaption);
1821 }
1822 }
1823
1824 if (!strHostResource.isEmpty())
1825 {
1826 //pItem->createChild("rasd:HostResource")->addContent(strHostResource);
1827 itemElementHelper = itemElement;
1828 pItemHelper = pItem->createChild(itemElementHelper.append("HostResource").c_str());
1829 pItemHelper->addContent(strHostResource);
1830 }
1831
1832 {
1833 // <rasd:InstanceID>1</rasd:InstanceID>
1834 itemElementHelper = itemElement;
1835 if (enFormat == ovf::OVFVersion_0_9)
1836 //pelmInstanceID = pItem->createChild("rasd:InstanceId");
1837 pItemHelper = pItem->createChild(itemElementHelper.append("InstanceId").c_str());
1838 else
1839 //pelmInstanceID = pItem->createChild("rasd:InstanceID"); // capitalization changed...
1840 pItemHelper = pItem->createChild(itemElementHelper.append("InstanceID").c_str());
1841
1842 pItemHelper->addContent(Utf8StrFmt("%d", ulInstanceID++));
1843 }
1844
1845 if (ulParent)
1846 {
1847 //pItem->createChild("rasd:Parent")->addContent(Utf8StrFmt("%d", ulParent));
1848 itemElementHelper = itemElement;
1849 pItemHelper = pItem->createChild(itemElementHelper.append("Parent").c_str());
1850 pItemHelper->addContent(Utf8StrFmt("%d", ulParent));
1851 }
1852
1853 if (!strResourceSubType.isEmpty())
1854 {
1855 //pItem->createChild("rasd:ResourceSubType")->addContent(strResourceSubType);
1856 itemElementHelper = itemElement;
1857 pItemHelper = pItem->createChild(itemElementHelper.append("ResourceSubType").c_str());
1858 pItemHelper->addContent(strResourceSubType);
1859 }
1860
1861 {
1862 // <rasd:ResourceType>3</rasd:ResourceType>
1863 //pItem->createChild("rasd:ResourceType")->addContent(Utf8StrFmt("%d", type));
1864 itemElementHelper = itemElement;
1865 pItemHelper = pItem->createChild(itemElementHelper.append("ResourceType").c_str());
1866 pItemHelper->addContent(Utf8StrFmt("%d", type));
1867 }
1868
1869 // <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
1870 if (lVirtualQuantity != -1)
1871 {
1872 //pItem->createChild("rasd:VirtualQuantity")->addContent(Utf8StrFmt("%d", lVirtualQuantity));
1873 itemElementHelper = itemElement;
1874 pItemHelper = pItem->createChild(itemElementHelper.append("VirtualQuantity").c_str());
1875 pItemHelper->addContent(Utf8StrFmt("%d", lVirtualQuantity));
1876 }
1877 }
1878 }
1879 } // for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
1880
1881 // now that we're done with the official OVF <Item> tags under <VirtualSystem>, write out VirtualBox XML
1882 // under the vbox: namespace
1883 xml::ElementNode *pelmVBoxMachine = pelmVirtualSystem->createChild("vbox:Machine");
1884 // ovf:required="false" tells other OVF parsers that they can ignore this thing
1885 pelmVBoxMachine->setAttribute("ovf:required", "false");
1886 // ovf:Info element is required or VMware will bail out on the vbox:Machine element
1887 pelmVBoxMachine->createChild("ovf:Info")->addContent("Complete VirtualBox machine configuration in VirtualBox format");
1888
1889 // create an empty machine config
1890 // use the same settings version as the current VM settings file
1891 settings::MachineConfigFile *pConfig = new settings::MachineConfigFile(&vsdescThis->m->pMachine->i_getSettingsFileFull());
1892
1893 writeLock.release();
1894 try
1895 {
1896 AutoWriteLock machineLock(vsdescThis->m->pMachine COMMA_LOCKVAL_SRC_POS);
1897 // fill the machine config
1898 vsdescThis->m->pMachine->i_copyMachineDataToSettings(*pConfig);
1899
1900 // Apply export tweaks to machine settings
1901 bool fStripAllMACs = m->optListExport.contains(ExportOptions_StripAllMACs);
1902 bool fStripAllNonNATMACs = m->optListExport.contains(ExportOptions_StripAllNonNATMACs);
1903 if (fStripAllMACs || fStripAllNonNATMACs)
1904 {
1905 for (settings::NetworkAdaptersList::iterator it = pConfig->hardwareMachine.llNetworkAdapters.begin();
1906 it != pConfig->hardwareMachine.llNetworkAdapters.end();
1907 ++it)
1908 {
1909 settings::NetworkAdapter &nic = *it;
1910 if (fStripAllMACs || (fStripAllNonNATMACs && nic.mode != NetworkAttachmentType_NAT))
1911 nic.strMACAddress.setNull();
1912 }
1913 }
1914
1915 // write the machine config to the vbox:Machine element
1916 pConfig->buildMachineXML(*pelmVBoxMachine,
1917 settings::MachineConfigFile::BuildMachineXML_WriteVBoxVersionAttribute
1918 /*| settings::MachineConfigFile::BuildMachineXML_SkipRemovableMedia*/
1919 | settings::MachineConfigFile::BuildMachineXML_SuppressSavedState,
1920 // but not BuildMachineXML_IncludeSnapshots nor BuildMachineXML_MediaRegistry
1921 pllElementsWithUuidAttributes);
1922 delete pConfig;
1923 }
1924 catch (...)
1925 {
1926 writeLock.acquire();
1927 delete pConfig;
1928 throw;
1929 }
1930 writeLock.acquire();
1931}
1932
1933/**
1934 * Actual worker code for writing out OVF/OVA to disk. This is called from Appliance::taskThreadWriteOVF()
1935 * and therefore runs on the OVF/OVA write worker thread.
1936 *
1937 * This runs in one context:
1938 *
1939 * 1) in a first worker thread; in that case, Appliance::Write() called Appliance::i_writeImpl();
1940 *
1941 * @param pTask
1942 * @return
1943 */
1944HRESULT Appliance::i_writeFS(TaskOVF *pTask)
1945{
1946 LogFlowFuncEnter();
1947 LogFlowFunc(("ENTER appliance %p\n", this));
1948
1949 AutoCaller autoCaller(this);
1950 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1951
1952 HRESULT rc = S_OK;
1953
1954 // Lock the media tree early to make sure nobody else tries to make changes
1955 // to the tree. Also lock the IAppliance object for writing.
1956 AutoMultiWriteLock2 multiLock(&mVirtualBox->i_getMediaTreeLockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
1957 // Additional protect the IAppliance object, cause we leave the lock
1958 // when starting the disk export and we don't won't block other
1959 // callers on this lengthy operations.
1960 m->state = Data::ApplianceExporting;
1961
1962 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
1963 rc = i_writeFSOVF(pTask, multiLock);
1964 else
1965 rc = i_writeFSOVA(pTask, multiLock);
1966
1967 // reset the state so others can call methods again
1968 m->state = Data::ApplianceIdle;
1969
1970 LogFlowFunc(("rc=%Rhrc\n", rc));
1971 LogFlowFuncLeave();
1972 return rc;
1973}
1974
1975HRESULT Appliance::i_writeFSOVF(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1976{
1977 LogFlowFuncEnter();
1978
1979 HRESULT rc = S_OK;
1980
1981 PVDINTERFACEIO pShaIo = 0;
1982 PVDINTERFACEIO pFileIo = 0;
1983 do
1984 {
1985 pShaIo = ShaCreateInterface();
1986 if (!pShaIo)
1987 {
1988 rc = E_OUTOFMEMORY;
1989 break;
1990 }
1991 pFileIo = FileCreateInterface();
1992 if (!pFileIo)
1993 {
1994 rc = E_OUTOFMEMORY;
1995 break;
1996 }
1997
1998 SHASTORAGE storage;
1999 RT_ZERO(storage);
2000 storage.fCreateDigest = m->fManifest;
2001 storage.fSha256 = m->fSha256;
2002
2003
2004 Utf8Str name = i_applianceIOName(applianceIOFile);
2005
2006 int vrc = VDInterfaceAdd(&pFileIo->Core, name.c_str(),
2007 VDINTERFACETYPE_IO, 0, sizeof(VDINTERFACEIO),
2008 &storage.pVDImageIfaces);
2009 if (RT_FAILURE(vrc))
2010 {
2011 rc = E_FAIL;
2012 break;
2013 }
2014 rc = i_writeFSImpl(pTask, writeLock, pShaIo, &storage);
2015 } while (0);
2016
2017 /* Cleanup */
2018 if (pShaIo)
2019 RTMemFree(pShaIo);
2020 if (pFileIo)
2021 RTMemFree(pFileIo);
2022
2023 LogFlowFuncLeave();
2024 return rc;
2025}
2026
2027HRESULT Appliance::i_writeFSOVA(TaskOVF *pTask, AutoWriteLockBase& writeLock)
2028{
2029 LogFlowFuncEnter();
2030
2031 RTTAR tar;
2032 int vrc = RTTarOpen(&tar, pTask->locInfo.strPath.c_str(), RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_ALL);
2033 if (RT_FAILURE(vrc))
2034 return setError(VBOX_E_FILE_ERROR,
2035 tr("Could not create OVA file '%s' (%Rrc)"),
2036 pTask->locInfo.strPath.c_str(), vrc);
2037
2038 HRESULT rc = S_OK;
2039
2040 PVDINTERFACEIO pShaIo = 0;
2041 PVDINTERFACEIO pTarIo = 0;
2042 do
2043 {
2044 pShaIo = ShaCreateInterface();
2045 if (!pShaIo)
2046 {
2047 rc = E_OUTOFMEMORY;
2048 break;
2049 }
2050 pTarIo = tarWriterCreateInterface();
2051 if (!pTarIo)
2052 {
2053 rc = E_OUTOFMEMORY;
2054 break;
2055 }
2056 SHASTORAGE storage;
2057 RT_ZERO(storage);
2058 storage.fCreateDigest = m->fManifest;
2059 storage.fSha256 = m->fSha256;
2060
2061 Utf8Str name = i_applianceIOName(applianceIOTar);
2062
2063 vrc = VDInterfaceAdd(&pTarIo->Core, name.c_str(),
2064 VDINTERFACETYPE_IO, tar, sizeof(VDINTERFACEIO),
2065 &storage.pVDImageIfaces);
2066
2067 if (RT_FAILURE(vrc))
2068 {
2069 rc = E_FAIL;
2070 break;
2071 }
2072 rc = i_writeFSImpl(pTask, writeLock, pShaIo, &storage);
2073 } while (0);
2074
2075 RTTarClose(tar);
2076
2077 /* Cleanup */
2078 if (pShaIo)
2079 RTMemFree(pShaIo);
2080 if (pTarIo)
2081 RTMemFree(pTarIo);
2082
2083 /* Delete ova file on error */
2084 if (FAILED(rc))
2085 RTFileDelete(pTask->locInfo.strPath.c_str());
2086
2087 LogFlowFuncLeave();
2088 return rc;
2089}
2090
2091HRESULT Appliance::i_writeFSImpl(TaskOVF *pTask, AutoWriteLockBase& writeLock, PVDINTERFACEIO pIfIo, PSHASTORAGE pStorage)
2092{
2093 LogFlowFuncEnter();
2094
2095 HRESULT rc = S_OK;
2096
2097 list<STRPAIR> fileList;
2098 try
2099 {
2100 int vrc;
2101 // the XML stack contains two maps for disks and networks, which allows us to
2102 // a) have a list of unique disk names (to make sure the same disk name is only added once)
2103 // and b) keep a list of all networks
2104 XMLStack stack;
2105 // Scope this to free the memory as soon as this is finished
2106 {
2107 // Create a xml document
2108 xml::Document doc;
2109 // Now fully build a valid ovf document in memory
2110 i_buildXML(writeLock, doc, stack, pTask->locInfo.strPath, pTask->enFormat);
2111 /* Extract the OVA file name */
2112 Utf8Str strOvaFile = pTask->locInfo.strPath;
2113 /* Extract the path */
2114 Utf8Str strOvfFile = strOvaFile.stripSuffix().append(".ovf");
2115 // Create a memory buffer containing the XML. */
2116 void *pvBuf = 0;
2117 size_t cbSize;
2118 xml::XmlMemWriter writer;
2119 writer.write(doc, &pvBuf, &cbSize);
2120 if (RT_UNLIKELY(!pvBuf))
2121 throw setError(VBOX_E_FILE_ERROR,
2122 tr("Could not create OVF file '%s'"),
2123 strOvfFile.c_str());
2124 /* Write the ovf file to disk. */
2125 vrc = writeBufferToFile(strOvfFile.c_str(), pvBuf, cbSize, pIfIo, pStorage);
2126 if (RT_FAILURE(vrc))
2127 throw setError(VBOX_E_FILE_ERROR,
2128 tr("Could not create OVF file '%s' (%Rrc)"),
2129 strOvfFile.c_str(), vrc);
2130 fileList.push_back(STRPAIR(strOvfFile, pStorage->strDigest));
2131 }
2132
2133 // We need a proper format description
2134 ComObjPtr<MediumFormat> formatTemp;
2135
2136 ComObjPtr<MediumFormat> format;
2137 // Scope for the AutoReadLock
2138 {
2139 SystemProperties *pSysProps = mVirtualBox->i_getSystemProperties();
2140 AutoReadLock propsLock(pSysProps COMMA_LOCKVAL_SRC_POS);
2141 // We are always exporting to VMDK stream optimized for now
2142 formatTemp = pSysProps->i_mediumFormatFromExtension("iso");
2143
2144 format = pSysProps->i_mediumFormat("VMDK");
2145 if (format.isNull())
2146 throw setError(VBOX_E_NOT_SUPPORTED,
2147 tr("Invalid medium storage format"));
2148 }
2149
2150 // Finally, write out the disks!
2151 map<Utf8Str, const VirtualSystemDescriptionEntry*>::const_iterator itS;
2152 for (itS = stack.mapDisks.begin();
2153 itS != stack.mapDisks.end();
2154 ++itS)
2155 {
2156 const VirtualSystemDescriptionEntry *pDiskEntry = itS->second;
2157
2158 // source path: where the VBox image is
2159 const Utf8Str &strSrcFilePath = pDiskEntry->strVBoxCurrent;
2160
2161 //skip empty Medium. In common, It's may be empty CD/DVD
2162 if (strSrcFilePath.isEmpty() ||
2163 pDiskEntry->skipIt == true)
2164 continue;
2165
2166 // Do NOT check here whether the file exists. findHardDisk will
2167 // figure that out, and filesystem-based tests are simply wrong
2168 // in the general case (think of iSCSI).
2169
2170 // clone the disk:
2171 ComObjPtr<Medium> pSourceDisk;
2172
2173 Log(("Finding source disk \"%s\"\n", strSrcFilePath.c_str()));
2174
2175 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2176 {
2177 rc = mVirtualBox->i_findHardDiskByLocation(strSrcFilePath, true, &pSourceDisk);
2178 if (FAILED(rc)) throw rc;
2179 }
2180 else//may be CD or DVD
2181 {
2182 rc = mVirtualBox->i_findDVDOrFloppyImage(DeviceType_DVD,
2183 NULL,
2184 strSrcFilePath,
2185 true,
2186 &pSourceDisk);
2187 if (FAILED(rc)) throw rc;
2188 }
2189
2190 Bstr uuidSource;
2191 rc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
2192 if (FAILED(rc)) throw rc;
2193 Guid guidSource(uuidSource);
2194
2195 // output filename
2196 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
2197 // target path needs to be composed from where the output OVF is
2198 Utf8Str strTargetFilePath(pTask->locInfo.strPath);
2199 strTargetFilePath.stripFilename()
2200 .append("/")
2201 .append(strTargetFileNameOnly);
2202
2203 // The exporting requests a lock on the media tree. So leave our lock temporary.
2204 writeLock.release();
2205 try
2206 {
2207 // advance to the next operation
2208 pTask->pProgress->SetNextOperation(BstrFmt(tr("Exporting to disk image '%s'"),
2209 RTPathFilename(strTargetFilePath.c_str())).raw(),
2210 pDiskEntry->ulSizeMB); // operation's weight, as set up
2211 // with the IProgress originally
2212
2213 // create a flat copy of the source disk image
2214 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2215 {
2216 ComObjPtr<Progress> pProgress2;
2217 pProgress2.createObject();
2218 rc = pProgress2->init(mVirtualBox, static_cast<IAppliance*>(this),
2219 BstrFmt(tr("Creating medium '%s'"),
2220 strTargetFilePath.c_str()).raw(), TRUE);
2221 if (FAILED(rc)) throw rc;
2222
2223 rc = pSourceDisk->i_exportFile(strTargetFilePath.c_str(),
2224 format,
2225 MediumVariant_VmdkStreamOptimized,
2226 m->m_pSecretKeyStore,
2227 pIfIo,
2228 pStorage,
2229 pProgress2);
2230 if (FAILED(rc)) throw rc;
2231
2232 ComPtr<IProgress> pProgress3(pProgress2);
2233 // now wait for the background disk operation to complete; this throws HRESULTs on error
2234 i_waitForAsyncProgress(pTask->pProgress, pProgress3);
2235 }
2236 else
2237 {
2238 //copy/clone CD/DVD image
2239 Assert(pDiskEntry->type == VirtualSystemDescriptionType_CDROM);
2240
2241 /* Read the ISO file and add one to OVA/OVF package */
2242 {
2243 void *pvStorage;
2244 RTFILE pFile = NULL;
2245 void *pvUser = pStorage;
2246
2247 vrc = pIfIo->pfnOpen(pvUser, strTargetFilePath.c_str(),
2248 RTFILE_O_OPEN_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_NONE,
2249 0,
2250 &pvStorage);
2251 if (RT_FAILURE(vrc))
2252 throw setError(VBOX_E_FILE_ERROR,
2253 tr("Could not create or open file '%s' (%Rrc)"),
2254 strTargetFilePath.c_str(), vrc);
2255
2256 vrc = RTFileOpen(&pFile,
2257 strSrcFilePath.c_str(),
2258 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
2259
2260 if (RT_FAILURE(vrc) || pFile == NULL)
2261 {
2262 pIfIo->pfnClose(pvUser, pvStorage);
2263 throw setError(VBOX_E_FILE_ERROR,
2264 tr("Could not create or open file '%s' (%Rrc)"),
2265 strSrcFilePath.c_str(), vrc);
2266 }
2267
2268 uint64_t cbFile = 0;
2269 vrc = RTFileGetSize(pFile, &cbFile);
2270 if (RT_SUCCESS(vrc))
2271 {
2272 size_t const cbTmpSize = _1M;
2273 void *pvTmpBuf = RTMemAlloc(cbTmpSize);
2274 if (pvTmpBuf)
2275 {
2276 /* The copy loop. */
2277 uint64_t offDstFile = 0;
2278 for (;;)
2279 {
2280 size_t cbChunk = 0;
2281 vrc = RTFileRead(pFile, pvTmpBuf, cbTmpSize, &cbChunk);
2282 if (RT_FAILURE(vrc) || cbChunk == 0)
2283 break;
2284
2285 size_t cbWritten = 0;
2286 vrc = pIfIo->pfnWriteSync(pvUser,
2287 pvStorage,
2288 offDstFile,
2289 pvTmpBuf,
2290 cbChunk,
2291 &cbWritten);
2292 if (RT_FAILURE(vrc))
2293 break;
2294 Assert(cbWritten == cbChunk);
2295
2296 offDstFile += cbWritten;
2297 }
2298
2299 RTMemFree(pvTmpBuf);
2300 }
2301 else
2302 vrc = VERR_NO_MEMORY;
2303 }
2304
2305 pIfIo->pfnClose(pvUser, pvStorage);
2306 RTFileClose(pFile);
2307
2308 if (RT_FAILURE(vrc))
2309 {
2310 if (vrc == VERR_EOF)
2311 vrc = VINF_SUCCESS;
2312 else
2313 throw setError(VBOX_E_FILE_ERROR,
2314 tr("Error during copy CD/DVD image '%s' (%Rrc)"),
2315 strSrcFilePath.c_str(), vrc);
2316 }
2317 }
2318 }
2319 }
2320 catch (HRESULT rc3)
2321 {
2322 writeLock.acquire();
2323 /// @todo file deletion on error? If not, we can remove that whole try/catch block.
2324 throw rc3;
2325 }
2326 // Finished, lock again (so nobody mess around with the medium tree
2327 // in the meantime)
2328 writeLock.acquire();
2329 fileList.push_back(STRPAIR(strTargetFilePath, pStorage->strDigest));
2330 }
2331
2332 if (m->fManifest)
2333 {
2334 // Create & write the manifest file
2335 Utf8Str strMfFilePath = Utf8Str(pTask->locInfo.strPath).stripSuffix().append(".mf");
2336 Utf8Str strMfFileName = Utf8Str(strMfFilePath).stripPath();
2337 pTask->pProgress->SetNextOperation(BstrFmt(tr("Creating manifest file '%s'"), strMfFileName.c_str()).raw(),
2338 m->ulWeightForManifestOperation); // operation's weight, as set up
2339 // with the IProgress originally);
2340 PRTMANIFESTTEST paManifestFiles = (PRTMANIFESTTEST)RTMemAlloc(sizeof(RTMANIFESTTEST) * fileList.size());
2341 size_t i = 0;
2342 list<STRPAIR>::const_iterator it1;
2343 for (it1 = fileList.begin();
2344 it1 != fileList.end();
2345 ++it1, ++i)
2346 {
2347 paManifestFiles[i].pszTestFile = (*it1).first.c_str();
2348 paManifestFiles[i].pszTestDigest = (*it1).second.c_str();
2349 }
2350 void *pvBuf;
2351 size_t cbSize;
2352 vrc = RTManifestWriteFilesBuf(&pvBuf, &cbSize, m->fSha256 ? RTDIGESTTYPE_SHA256 : RTDIGESTTYPE_SHA1,
2353 paManifestFiles, fileList.size());
2354 RTMemFree(paManifestFiles);
2355 if (RT_FAILURE(vrc))
2356 throw setError(VBOX_E_FILE_ERROR,
2357 tr("Could not create manifest file '%s' (%Rrc)"),
2358 strMfFileName.c_str(), vrc);
2359 /* Disable digest creation for the manifest file. */
2360 pStorage->fCreateDigest = false;
2361 /* Write the manifest file to disk. */
2362 vrc = writeBufferToFile(strMfFilePath.c_str(), pvBuf, cbSize, pIfIo, pStorage);
2363 RTMemFree(pvBuf);
2364 if (RT_FAILURE(vrc))
2365 throw setError(VBOX_E_FILE_ERROR,
2366 tr("Could not create manifest file '%s' (%Rrc)"),
2367 strMfFilePath.c_str(), vrc);
2368 }
2369 }
2370 catch (RTCError &x) // includes all XML exceptions
2371 {
2372 rc = setError(VBOX_E_FILE_ERROR,
2373 x.what());
2374 }
2375 catch (HRESULT aRC)
2376 {
2377 rc = aRC;
2378 }
2379
2380 /* Cleanup on error */
2381 if (FAILED(rc))
2382 {
2383 list<STRPAIR>::const_iterator it1;
2384 for (it1 = fileList.begin();
2385 it1 != fileList.end();
2386 ++it1)
2387 pIfIo->pfnDelete(pStorage, (*it1).first.c_str());
2388 }
2389
2390 LogFlowFunc(("rc=%Rhrc\n", rc));
2391 LogFlowFuncLeave();
2392
2393 return rc;
2394}
2395
Note: See TracBrowser for help on using the repository browser.

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