VirtualBox

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

Last change on this file since 65809 was 65807, checked in by vboxsync, 8 years ago

bugref:8743. Workaround for correct OVF export VMs which share one or more virtual disks among them. This issue is tied with the part <vbox:machine> in the OVF description file.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 106.3 KB
Line 
1/* $Id: ApplianceImplExport.cpp 65807 2017-02-20 10:28:47Z 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%.3d.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%.3d.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 uint32_t ulFile = 1;
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 list<Utf8Str> diskList;
923 list<Utf8Str>::const_iterator itS;
924
925 for (itS = stack.mapDiskSequenceForOneVM.begin();
926 itS != stack.mapDiskSequenceForOneVM.end();
927 ++itS)
928 {
929 const Utf8Str &strDiskID = *itS;
930 const VirtualSystemDescriptionEntry *pDiskEntry = stack.mapDisks[strDiskID];
931
932 // source path: where the VBox image is
933 const Utf8Str &strSrcFilePath = pDiskEntry->strVBoxCurrent;
934 Bstr bstrSrcFilePath(strSrcFilePath);
935
936 //skip empty Medium. There are no information to add into section <References> or <DiskSection>
937 if (strSrcFilePath.isEmpty() ||
938 pDiskEntry->skipIt == true)
939 continue;
940
941 // Do NOT check here whether the file exists. FindMedium will figure
942 // that out, and filesystem-based tests are simply wrong in the
943 // general case (think of iSCSI).
944
945 // We need some info from the source disks
946 ComPtr<IMedium> pSourceDisk;
947 //DeviceType_T deviceType = DeviceType_HardDisk;// by default
948
949 Log(("Finding source disk \"%ls\"\n", bstrSrcFilePath.raw()));
950
951 HRESULT rc;
952
953 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
954 {
955 rc = mVirtualBox->OpenMedium(bstrSrcFilePath.raw(),
956 DeviceType_HardDisk,
957 AccessMode_ReadWrite,
958 FALSE /* fForceNewUuid */,
959 pSourceDisk.asOutParam());
960 if (FAILED(rc))
961 throw rc;
962 }
963 else if (pDiskEntry->type == VirtualSystemDescriptionType_CDROM)//may be, this is CD/DVD
964 {
965 rc = mVirtualBox->OpenMedium(bstrSrcFilePath.raw(),
966 DeviceType_DVD,
967 AccessMode_ReadOnly,
968 FALSE,
969 pSourceDisk.asOutParam());
970 if (FAILED(rc))
971 throw rc;
972 }
973
974 Bstr uuidSource;
975 rc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
976 if (FAILED(rc)) throw rc;
977 Guid guidSource(uuidSource);
978
979 // output filename
980 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
981 // target path needs to be composed from where the output OVF is
982 Utf8Str strTargetFilePath(strPath);
983 strTargetFilePath.stripFilename();
984 strTargetFilePath.append("/");
985 strTargetFilePath.append(strTargetFileNameOnly);
986
987 // We are always exporting to VMDK stream optimized for now
988 //Bstr bstrSrcFormat = L"VMDK";//not used
989
990 diskList.push_back(strTargetFilePath);
991
992 LONG64 cbCapacity = 0; // size reported to guest
993 rc = pSourceDisk->COMGETTER(LogicalSize)(&cbCapacity);
994 if (FAILED(rc)) throw rc;
995 /// @todo r=poetzsch: wrong it is reported in bytes ...
996 // capacity is reported in megabytes, so...
997 //cbCapacity *= _1M;
998
999 Guid guidTarget; /* Creates a new uniq number for the target disk. */
1000 guidTarget.create();
1001
1002 // now handle the XML for the disk:
1003 Utf8StrFmt strFileRef("file%RI32", ulFile++);
1004 // <File ovf:href="WindowsXpProfessional-disk1.vmdk" ovf:id="file1" ovf:size="1710381056"/>
1005 xml::ElementNode *pelmFile = pelmReferences->createChild("File");
1006 pelmFile->setAttribute("ovf:id", strFileRef);
1007 pelmFile->setAttribute("ovf:href", strTargetFileNameOnly);
1008 /// @todo the actual size is not available at this point of time,
1009 // cause the disk will be compressed. The 1.0 standard says this is
1010 // optional! 1.1 isn't fully clear if the "gzip" format is used.
1011 // Need to be checked. */
1012 // pelmFile->setAttribute("ovf:size", Utf8StrFmt("%RI64", cbFile).c_str());
1013
1014 // add disk to XML Disks section
1015 // <Disk ovf:capacity="8589934592" ovf:diskId="vmdisk1" ovf:fileRef="file1" ovf:format="..."/>
1016 xml::ElementNode *pelmDisk = pelmDiskSection->createChild("Disk");
1017 pelmDisk->setAttribute("ovf:capacity", Utf8StrFmt("%RI64", cbCapacity).c_str());
1018 pelmDisk->setAttribute("ovf:diskId", strDiskID);
1019 pelmDisk->setAttribute("ovf:fileRef", strFileRef);
1020
1021 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)//deviceType == DeviceType_HardDisk
1022 {
1023 pelmDisk->setAttribute("ovf:format",
1024 (enFormat == ovf::OVFVersion_0_9)
1025 ? "http://www.vmware.com/specifications/vmdk.html#sparse" // must be sparse or ovftoo
1026 : "http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized"
1027 // correct string as communicated to us by VMware (public bug #6612)
1028 );
1029 }
1030 else //pDiskEntry->type == VirtualSystemDescriptionType_CDROM, deviceType == DeviceType_DVD
1031 {
1032 pelmDisk->setAttribute("ovf:format",
1033 "http://www.ecma-international.org/publications/standards/Ecma-119.htm"
1034 );
1035 }
1036
1037 // add the UUID of the newly target image to the OVF disk element, but in the
1038 // vbox: namespace since it's not part of the standard
1039 pelmDisk->setAttribute("vbox:uuid", Utf8StrFmt("%RTuuid", guidTarget.raw()).c_str());
1040
1041 // now, we might have other XML elements from vbox:Machine pointing to this image,
1042 // but those would refer to the UUID of the _source_ image (which we created the
1043 // export image from); those UUIDs need to be fixed to the export image
1044 Utf8Str strGuidSourceCurly = guidSource.toStringCurly();
1045 for (std::list<xml::ElementNode*>::iterator eit = llElementsWithUuidAttributes.begin();
1046 eit != llElementsWithUuidAttributes.end();
1047 ++eit)
1048 {
1049 xml::ElementNode *pelmImage = *eit;
1050 Utf8Str strUUID;
1051 pelmImage->getAttributeValue("uuid", strUUID);
1052 if (strUUID == strGuidSourceCurly)
1053 // overwrite existing uuid attribute
1054 pelmImage->setAttribute("uuid", guidTarget.toStringCurly());
1055 }
1056 }
1057 llElementsWithUuidAttributes.clear();
1058 stack.mapDiskSequenceForOneVM.clear();
1059 }
1060
1061 // now, fill in the network section we set up empty above according
1062 // to the networks we found with the hardware items
1063 map<Utf8Str, bool>::const_iterator itN;
1064 for (itN = stack.mapNetworks.begin();
1065 itN != stack.mapNetworks.end();
1066 ++itN)
1067 {
1068 const Utf8Str &strNetwork = itN->first;
1069 xml::ElementNode *pelmNetwork = pelmNetworkSection->createChild("Network");
1070 pelmNetwork->setAttribute("ovf:name", strNetwork.c_str());
1071 pelmNetwork->createChild("Description")->addContent("Logical network used by this appliance.");
1072 }
1073
1074}
1075
1076/**
1077 * Called from Appliance::i_buildXML() for each virtual system (machine) that
1078 * needs XML written out.
1079 *
1080 * @param writeLock The current write lock.
1081 * @param elmToAddVirtualSystemsTo XML element to append elements to.
1082 * @param pllElementsWithUuidAttributes out: list of XML elements produced here
1083 * with UUID attributes for quick
1084 * fixing by caller later
1085 * @param vsdescThis The IVirtualSystemDescription
1086 * instance for which to write XML.
1087 * @param enFormat OVF format (0.9 or 1.0).
1088 * @param stack Structure for temporary private
1089 * data shared with caller.
1090 */
1091void Appliance::i_buildXMLForOneVirtualSystem(AutoWriteLockBase& writeLock,
1092 xml::ElementNode &elmToAddVirtualSystemsTo,
1093 std::list<xml::ElementNode*> *pllElementsWithUuidAttributes,
1094 ComObjPtr<VirtualSystemDescription> &vsdescThis,
1095 ovf::OVFVersion_T enFormat,
1096 XMLStack &stack)
1097{
1098 LogFlowFunc(("ENTER appliance %p\n", this));
1099
1100 xml::ElementNode *pelmVirtualSystem;
1101 if (enFormat == ovf::OVFVersion_0_9)
1102 {
1103 // <Section xsi:type="ovf:NetworkSection_Type">
1104 pelmVirtualSystem = elmToAddVirtualSystemsTo.createChild("Content");
1105 pelmVirtualSystem->setAttribute("xsi:type", "ovf:VirtualSystem_Type");
1106 }
1107 else
1108 pelmVirtualSystem = elmToAddVirtualSystemsTo.createChild("VirtualSystem");
1109
1110 /*xml::ElementNode *pelmVirtualSystemInfo =*/ pelmVirtualSystem->createChild("Info")->addContent("A virtual machine");
1111
1112 std::list<VirtualSystemDescriptionEntry*> llName = vsdescThis->i_findByType(VirtualSystemDescriptionType_Name);
1113 if (llName.empty())
1114 throw setError(VBOX_E_NOT_SUPPORTED, tr("Missing VM name"));
1115 Utf8Str &strVMName = llName.back()->strVBoxCurrent;
1116 pelmVirtualSystem->setAttribute("ovf:id", strVMName);
1117
1118 // product info
1119 std::list<VirtualSystemDescriptionEntry*> llProduct = vsdescThis->i_findByType(VirtualSystemDescriptionType_Product);
1120 std::list<VirtualSystemDescriptionEntry*> llProductUrl = vsdescThis->i_findByType(VirtualSystemDescriptionType_ProductUrl);
1121 std::list<VirtualSystemDescriptionEntry*> llVendor = vsdescThis->i_findByType(VirtualSystemDescriptionType_Vendor);
1122 std::list<VirtualSystemDescriptionEntry*> llVendorUrl = vsdescThis->i_findByType(VirtualSystemDescriptionType_VendorUrl);
1123 std::list<VirtualSystemDescriptionEntry*> llVersion = vsdescThis->i_findByType(VirtualSystemDescriptionType_Version);
1124 bool fProduct = llProduct.size() && !llProduct.back()->strVBoxCurrent.isEmpty();
1125 bool fProductUrl = llProductUrl.size() && !llProductUrl.back()->strVBoxCurrent.isEmpty();
1126 bool fVendor = llVendor.size() && !llVendor.back()->strVBoxCurrent.isEmpty();
1127 bool fVendorUrl = llVendorUrl.size() && !llVendorUrl.back()->strVBoxCurrent.isEmpty();
1128 bool fVersion = llVersion.size() && !llVersion.back()->strVBoxCurrent.isEmpty();
1129 if (fProduct || fProductUrl || fVendor || fVendorUrl || fVersion)
1130 {
1131 /* <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
1132 <Info>Meta-information about the installed software</Info>
1133 <Product>VAtest</Product>
1134 <Vendor>SUN Microsystems</Vendor>
1135 <Version>10.0</Version>
1136 <ProductUrl>http://blogs.sun.com/VirtualGuru</ProductUrl>
1137 <VendorUrl>http://www.sun.com</VendorUrl>
1138 </Section> */
1139 xml::ElementNode *pelmAnnotationSection;
1140 if (enFormat == ovf::OVFVersion_0_9)
1141 {
1142 // <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
1143 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
1144 pelmAnnotationSection->setAttribute("xsi:type", "ovf:ProductSection_Type");
1145 }
1146 else
1147 pelmAnnotationSection = pelmVirtualSystem->createChild("ProductSection");
1148
1149 pelmAnnotationSection->createChild("Info")->addContent("Meta-information about the installed software");
1150 if (fProduct)
1151 pelmAnnotationSection->createChild("Product")->addContent(llProduct.back()->strVBoxCurrent);
1152 if (fVendor)
1153 pelmAnnotationSection->createChild("Vendor")->addContent(llVendor.back()->strVBoxCurrent);
1154 if (fVersion)
1155 pelmAnnotationSection->createChild("Version")->addContent(llVersion.back()->strVBoxCurrent);
1156 if (fProductUrl)
1157 pelmAnnotationSection->createChild("ProductUrl")->addContent(llProductUrl.back()->strVBoxCurrent);
1158 if (fVendorUrl)
1159 pelmAnnotationSection->createChild("VendorUrl")->addContent(llVendorUrl.back()->strVBoxCurrent);
1160 }
1161
1162 // description
1163 std::list<VirtualSystemDescriptionEntry*> llDescription = vsdescThis->i_findByType(VirtualSystemDescriptionType_Description);
1164 if (llDescription.size() &&
1165 !llDescription.back()->strVBoxCurrent.isEmpty())
1166 {
1167 /* <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
1168 <Info>A human-readable annotation</Info>
1169 <Annotation>Plan 9</Annotation>
1170 </Section> */
1171 xml::ElementNode *pelmAnnotationSection;
1172 if (enFormat == ovf::OVFVersion_0_9)
1173 {
1174 // <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
1175 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
1176 pelmAnnotationSection->setAttribute("xsi:type", "ovf:AnnotationSection_Type");
1177 }
1178 else
1179 pelmAnnotationSection = pelmVirtualSystem->createChild("AnnotationSection");
1180
1181 pelmAnnotationSection->createChild("Info")->addContent("A human-readable annotation");
1182 pelmAnnotationSection->createChild("Annotation")->addContent(llDescription.back()->strVBoxCurrent);
1183 }
1184
1185 // license
1186 std::list<VirtualSystemDescriptionEntry*> llLicense = vsdescThis->i_findByType(VirtualSystemDescriptionType_License);
1187 if (llLicense.size() &&
1188 !llLicense.back()->strVBoxCurrent.isEmpty())
1189 {
1190 /* <EulaSection>
1191 <Info ovf:msgid="6">License agreement for the Virtual System.</Info>
1192 <License ovf:msgid="1">License terms can go in here.</License>
1193 </EulaSection> */
1194 xml::ElementNode *pelmEulaSection;
1195 if (enFormat == ovf::OVFVersion_0_9)
1196 {
1197 pelmEulaSection = pelmVirtualSystem->createChild("Section");
1198 pelmEulaSection->setAttribute("xsi:type", "ovf:EulaSection_Type");
1199 }
1200 else
1201 pelmEulaSection = pelmVirtualSystem->createChild("EulaSection");
1202
1203 pelmEulaSection->createChild("Info")->addContent("License agreement for the virtual system");
1204 pelmEulaSection->createChild("License")->addContent(llLicense.back()->strVBoxCurrent);
1205 }
1206
1207 // operating system
1208 std::list<VirtualSystemDescriptionEntry*> llOS = vsdescThis->i_findByType(VirtualSystemDescriptionType_OS);
1209 if (llOS.empty())
1210 throw setError(VBOX_E_NOT_SUPPORTED, tr("Missing OS type"));
1211 /* <OperatingSystemSection ovf:id="82">
1212 <Info>Guest Operating System</Info>
1213 <Description>Linux 2.6.x</Description>
1214 </OperatingSystemSection> */
1215 VirtualSystemDescriptionEntry *pvsdeOS = llOS.back();
1216 xml::ElementNode *pelmOperatingSystemSection;
1217 if (enFormat == ovf::OVFVersion_0_9)
1218 {
1219 pelmOperatingSystemSection = pelmVirtualSystem->createChild("Section");
1220 pelmOperatingSystemSection->setAttribute("xsi:type", "ovf:OperatingSystemSection_Type");
1221 }
1222 else
1223 pelmOperatingSystemSection = pelmVirtualSystem->createChild("OperatingSystemSection");
1224
1225 pelmOperatingSystemSection->setAttribute("ovf:id", pvsdeOS->strOvf);
1226 pelmOperatingSystemSection->createChild("Info")->addContent("The kind of installed guest operating system");
1227 Utf8Str strOSDesc;
1228 convertCIMOSType2VBoxOSType(strOSDesc, (ovf::CIMOSType_T)pvsdeOS->strOvf.toInt32(), "");
1229 pelmOperatingSystemSection->createChild("Description")->addContent(strOSDesc);
1230 // add the VirtualBox ostype in a custom tag in a different namespace
1231 xml::ElementNode *pelmVBoxOSType = pelmOperatingSystemSection->createChild("vbox:OSType");
1232 pelmVBoxOSType->setAttribute("ovf:required", "false");
1233 pelmVBoxOSType->addContent(pvsdeOS->strVBoxCurrent);
1234
1235 // <VirtualHardwareSection ovf:id="hw1" ovf:transport="iso">
1236 xml::ElementNode *pelmVirtualHardwareSection;
1237 if (enFormat == ovf::OVFVersion_0_9)
1238 {
1239 // <Section xsi:type="ovf:VirtualHardwareSection_Type">
1240 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("Section");
1241 pelmVirtualHardwareSection->setAttribute("xsi:type", "ovf:VirtualHardwareSection_Type");
1242 }
1243 else
1244 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("VirtualHardwareSection");
1245
1246 pelmVirtualHardwareSection->createChild("Info")->addContent("Virtual hardware requirements for a virtual machine");
1247
1248 /* <System>
1249 <vssd:Description>Description of the virtual hardware section.</vssd:Description>
1250 <vssd:ElementName>vmware</vssd:ElementName>
1251 <vssd:InstanceID>1</vssd:InstanceID>
1252 <vssd:VirtualSystemIdentifier>MyLampService</vssd:VirtualSystemIdentifier>
1253 <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
1254 </System> */
1255 xml::ElementNode *pelmSystem = pelmVirtualHardwareSection->createChild("System");
1256
1257 pelmSystem->createChild("vssd:ElementName")->addContent("Virtual Hardware Family"); // required OVF 1.0
1258
1259 // <vssd:InstanceId>0</vssd:InstanceId>
1260 if (enFormat == ovf::OVFVersion_0_9)
1261 pelmSystem->createChild("vssd:InstanceId")->addContent("0");
1262 else // capitalization changed...
1263 pelmSystem->createChild("vssd:InstanceID")->addContent("0");
1264
1265 // <vssd:VirtualSystemIdentifier>VAtest</vssd:VirtualSystemIdentifier>
1266 pelmSystem->createChild("vssd:VirtualSystemIdentifier")->addContent(strVMName);
1267 // <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
1268 const char *pcszHardware = "virtualbox-2.2";
1269 if (enFormat == ovf::OVFVersion_0_9)
1270 // pretend to be vmware compatible then
1271 pcszHardware = "vmx-6";
1272 pelmSystem->createChild("vssd:VirtualSystemType")->addContent(pcszHardware);
1273
1274 // loop thru all description entries twice; once to write out all
1275 // devices _except_ disk images, and a second time to assign the
1276 // disk images; this is because disk images need to reference
1277 // IDE controllers, and we can't know their instance IDs without
1278 // assigning them first
1279
1280 uint32_t idIDEPrimaryController = 0;
1281 int32_t lIDEPrimaryControllerIndex = 0;
1282 uint32_t idIDESecondaryController = 0;
1283 int32_t lIDESecondaryControllerIndex = 0;
1284 uint32_t idSATAController = 0;
1285 int32_t lSATAControllerIndex = 0;
1286 uint32_t idSCSIController = 0;
1287 int32_t lSCSIControllerIndex = 0;
1288
1289 uint32_t ulInstanceID = 1;
1290
1291 uint32_t cDVDs = 0;
1292
1293 for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
1294 {
1295 int32_t lIndexThis = 0;
1296 vector<VirtualSystemDescriptionEntry>::const_iterator itD;
1297 for (itD = vsdescThis->m->maDescriptions.begin();
1298 itD != vsdescThis->m->maDescriptions.end();
1299 ++itD, ++lIndexThis)
1300 {
1301 const VirtualSystemDescriptionEntry &desc = *itD;
1302
1303 LogFlowFunc(("Loop %u: handling description entry ulIndex=%u, type=%s, strRef=%s, strOvf=%s, strVBox=%s, strExtraConfig=%s\n",
1304 uLoop,
1305 desc.ulIndex,
1306 ( desc.type == VirtualSystemDescriptionType_HardDiskControllerIDE ? "HardDiskControllerIDE"
1307 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSATA ? "HardDiskControllerSATA"
1308 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSCSI ? "HardDiskControllerSCSI"
1309 : desc.type == VirtualSystemDescriptionType_HardDiskControllerSAS ? "HardDiskControllerSAS"
1310 : desc.type == VirtualSystemDescriptionType_HardDiskImage ? "HardDiskImage"
1311 : Utf8StrFmt("%d", desc.type).c_str()),
1312 desc.strRef.c_str(),
1313 desc.strOvf.c_str(),
1314 desc.strVBoxCurrent.c_str(),
1315 desc.strExtraConfigCurrent.c_str()));
1316
1317 ovf::ResourceType_T type = (ovf::ResourceType_T)0; // if this becomes != 0 then we do stuff
1318 Utf8Str strResourceSubType;
1319
1320 Utf8Str strDescription; // results in <rasd:Description>...</rasd:Description> block
1321 Utf8Str strCaption; // results in <rasd:Caption>...</rasd:Caption> block
1322
1323 uint32_t ulParent = 0;
1324
1325 int32_t lVirtualQuantity = -1;
1326 Utf8Str strAllocationUnits;
1327
1328 int32_t lAddress = -1;
1329 int32_t lBusNumber = -1;
1330 int32_t lAddressOnParent = -1;
1331
1332 int32_t lAutomaticAllocation = -1; // 0 means "false", 1 means "true"
1333 Utf8Str strConnection; // results in <rasd:Connection>...</rasd:Connection> block
1334 Utf8Str strHostResource;
1335
1336 uint64_t uTemp;
1337
1338 ovf::VirtualHardwareItem vhi;
1339 ovf::StorageItem si;
1340 ovf::EthernetPortItem epi;
1341
1342 switch (desc.type)
1343 {
1344 case VirtualSystemDescriptionType_CPU:
1345 /* <Item>
1346 <rasd:Caption>1 virtual CPU</rasd:Caption>
1347 <rasd:Description>Number of virtual CPUs</rasd:Description>
1348 <rasd:ElementName>virtual CPU</rasd:ElementName>
1349 <rasd:InstanceID>1</rasd:InstanceID>
1350 <rasd:ResourceType>3</rasd:ResourceType>
1351 <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
1352 </Item> */
1353 if (uLoop == 1)
1354 {
1355 strDescription = "Number of virtual CPUs";
1356 type = ovf::ResourceType_Processor; // 3
1357 desc.strVBoxCurrent.toInt(uTemp);
1358 lVirtualQuantity = (int32_t)uTemp;
1359 strCaption = Utf8StrFmt("%d virtual CPU", lVirtualQuantity); // without this ovftool
1360 // won't eat the item
1361 }
1362 break;
1363
1364 case VirtualSystemDescriptionType_Memory:
1365 /* <Item>
1366 <rasd:AllocationUnits>MegaBytes</rasd:AllocationUnits>
1367 <rasd:Caption>256 MB of memory</rasd:Caption>
1368 <rasd:Description>Memory Size</rasd:Description>
1369 <rasd:ElementName>Memory</rasd:ElementName>
1370 <rasd:InstanceID>2</rasd:InstanceID>
1371 <rasd:ResourceType>4</rasd:ResourceType>
1372 <rasd:VirtualQuantity>256</rasd:VirtualQuantity>
1373 </Item> */
1374 if (uLoop == 1)
1375 {
1376 strDescription = "Memory Size";
1377 type = ovf::ResourceType_Memory; // 4
1378 desc.strVBoxCurrent.toInt(uTemp);
1379 lVirtualQuantity = (int32_t)(uTemp / _1M);
1380 strAllocationUnits = "MegaBytes";
1381 strCaption = Utf8StrFmt("%d MB of memory", lVirtualQuantity); // without this ovftool
1382 // won't eat the item
1383 }
1384 break;
1385
1386 case VirtualSystemDescriptionType_HardDiskControllerIDE:
1387 /* <Item>
1388 <rasd:Caption>ideController1</rasd:Caption>
1389 <rasd:Description>IDE Controller</rasd:Description>
1390 <rasd:InstanceId>5</rasd:InstanceId>
1391 <rasd:ResourceType>5</rasd:ResourceType>
1392 <rasd:Address>1</rasd:Address>
1393 <rasd:BusNumber>1</rasd:BusNumber>
1394 </Item> */
1395 if (uLoop == 1)
1396 {
1397 strDescription = "IDE Controller";
1398 type = ovf::ResourceType_IDEController; // 5
1399 strResourceSubType = desc.strVBoxCurrent;
1400
1401 if (!lIDEPrimaryControllerIndex)
1402 {
1403 // first IDE controller:
1404 strCaption = "ideController0";
1405 lAddress = 0;
1406 lBusNumber = 0;
1407 // remember this ID
1408 idIDEPrimaryController = ulInstanceID;
1409 lIDEPrimaryControllerIndex = lIndexThis;
1410 }
1411 else
1412 {
1413 // second IDE controller:
1414 strCaption = "ideController1";
1415 lAddress = 1;
1416 lBusNumber = 1;
1417 // remember this ID
1418 idIDESecondaryController = ulInstanceID;
1419 lIDESecondaryControllerIndex = lIndexThis;
1420 }
1421 }
1422 break;
1423
1424 case VirtualSystemDescriptionType_HardDiskControllerSATA:
1425 /* <Item>
1426 <rasd:Caption>sataController0</rasd:Caption>
1427 <rasd:Description>SATA Controller</rasd:Description>
1428 <rasd:InstanceId>4</rasd:InstanceId>
1429 <rasd:ResourceType>20</rasd:ResourceType>
1430 <rasd:ResourceSubType>ahci</rasd:ResourceSubType>
1431 <rasd:Address>0</rasd:Address>
1432 <rasd:BusNumber>0</rasd:BusNumber>
1433 </Item>
1434 */
1435 if (uLoop == 1)
1436 {
1437 strDescription = "SATA Controller";
1438 strCaption = "sataController0";
1439 type = ovf::ResourceType_OtherStorageDevice; // 20
1440 // it seems that OVFTool always writes these two, and since we can only
1441 // have one SATA controller, we'll use this as well
1442 lAddress = 0;
1443 lBusNumber = 0;
1444
1445 if ( desc.strVBoxCurrent.isEmpty() // AHCI is the default in VirtualBox
1446 || (!desc.strVBoxCurrent.compare("ahci", Utf8Str::CaseInsensitive))
1447 )
1448 strResourceSubType = "AHCI";
1449 else
1450 throw setError(VBOX_E_NOT_SUPPORTED,
1451 tr("Invalid config string \"%s\" in SATA controller"), desc.strVBoxCurrent.c_str());
1452
1453 // remember this ID
1454 idSATAController = ulInstanceID;
1455 lSATAControllerIndex = lIndexThis;
1456 }
1457 break;
1458
1459 case VirtualSystemDescriptionType_HardDiskControllerSCSI:
1460 case VirtualSystemDescriptionType_HardDiskControllerSAS:
1461 /* <Item>
1462 <rasd:Caption>scsiController0</rasd:Caption>
1463 <rasd:Description>SCSI Controller</rasd:Description>
1464 <rasd:InstanceId>4</rasd:InstanceId>
1465 <rasd:ResourceType>6</rasd:ResourceType>
1466 <rasd:ResourceSubType>buslogic</rasd:ResourceSubType>
1467 <rasd:Address>0</rasd:Address>
1468 <rasd:BusNumber>0</rasd:BusNumber>
1469 </Item>
1470 */
1471 if (uLoop == 1)
1472 {
1473 strDescription = "SCSI Controller";
1474 strCaption = "scsiController0";
1475 type = ovf::ResourceType_ParallelSCSIHBA; // 6
1476 // it seems that OVFTool always writes these two, and since we can only
1477 // have one SATA controller, we'll use this as well
1478 lAddress = 0;
1479 lBusNumber = 0;
1480
1481 if ( desc.strVBoxCurrent.isEmpty() // LsiLogic is the default in VirtualBox
1482 || (!desc.strVBoxCurrent.compare("lsilogic", Utf8Str::CaseInsensitive))
1483 )
1484 strResourceSubType = "lsilogic";
1485 else if (!desc.strVBoxCurrent.compare("buslogic", Utf8Str::CaseInsensitive))
1486 strResourceSubType = "buslogic";
1487 else if (!desc.strVBoxCurrent.compare("lsilogicsas", Utf8Str::CaseInsensitive))
1488 strResourceSubType = "lsilogicsas";
1489 else
1490 throw setError(VBOX_E_NOT_SUPPORTED,
1491 tr("Invalid config string \"%s\" in SCSI/SAS controller"),
1492 desc.strVBoxCurrent.c_str());
1493
1494 // remember this ID
1495 idSCSIController = ulInstanceID;
1496 lSCSIControllerIndex = lIndexThis;
1497 }
1498 break;
1499
1500 case VirtualSystemDescriptionType_HardDiskImage:
1501 /* <Item>
1502 <rasd:Caption>disk1</rasd:Caption>
1503 <rasd:InstanceId>8</rasd:InstanceId>
1504 <rasd:ResourceType>17</rasd:ResourceType>
1505 <rasd:HostResource>/disk/vmdisk1</rasd:HostResource>
1506 <rasd:Parent>4</rasd:Parent>
1507 <rasd:AddressOnParent>0</rasd:AddressOnParent>
1508 </Item> */
1509 if (uLoop == 2)
1510 {
1511 uint32_t cDisks = (uint32_t)stack.mapDisks.size();
1512 Utf8Str strDiskID = Utf8StrFmt("vmdisk%RI32", ++cDisks);
1513
1514 strDescription = "Disk Image";
1515 strCaption = Utf8StrFmt("disk%RI32", cDisks); // this is not used for anything else
1516 type = ovf::ResourceType_HardDisk; // 17
1517
1518 // the following references the "<Disks>" XML block
1519 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
1520
1521 // controller=<index>;channel=<c>
1522 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1523 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1524 int32_t lControllerIndex = -1;
1525 if (pos1 != Utf8Str::npos)
1526 {
1527 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1528 if (lControllerIndex == lIDEPrimaryControllerIndex)
1529 ulParent = idIDEPrimaryController;
1530 else if (lControllerIndex == lIDESecondaryControllerIndex)
1531 ulParent = idIDESecondaryController;
1532 else if (lControllerIndex == lSCSIControllerIndex)
1533 ulParent = idSCSIController;
1534 else if (lControllerIndex == lSATAControllerIndex)
1535 ulParent = idSATAController;
1536 }
1537 if (pos2 != Utf8Str::npos)
1538 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1539
1540 LogFlowFunc(("HardDiskImage details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1541 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex, lIDESecondaryControllerIndex,
1542 ulParent, lAddressOnParent));
1543
1544 if ( !ulParent
1545 || lAddressOnParent == -1
1546 )
1547 throw setError(VBOX_E_NOT_SUPPORTED,
1548 tr("Missing or bad extra config string in hard disk image: \"%s\""),
1549 desc.strExtraConfigCurrent.c_str());
1550
1551 stack.mapDisks[strDiskID] = &desc;
1552
1553 //use the list stack.mapDiskSequence where the disks go as the "VirtualSystem" should be placed
1554 //in the OVF description file.
1555 stack.mapDiskSequence.push_back(strDiskID);
1556 stack.mapDiskSequenceForOneVM.push_back(strDiskID);
1557 }
1558 break;
1559
1560 case VirtualSystemDescriptionType_Floppy:
1561 if (uLoop == 1)
1562 {
1563 strDescription = "Floppy Drive";
1564 strCaption = "floppy0"; // this is what OVFTool writes
1565 type = ovf::ResourceType_FloppyDrive; // 14
1566 lAutomaticAllocation = 0;
1567 lAddressOnParent = 0; // this is what OVFTool writes
1568 }
1569 break;
1570
1571 case VirtualSystemDescriptionType_CDROM:
1572 /* <Item>
1573 <rasd:Caption>cdrom1</rasd:Caption>
1574 <rasd:InstanceId>8</rasd:InstanceId>
1575 <rasd:ResourceType>15</rasd:ResourceType>
1576 <rasd:HostResource>/disk/cdrom1</rasd:HostResource>
1577 <rasd:Parent>4</rasd:Parent>
1578 <rasd:AddressOnParent>0</rasd:AddressOnParent>
1579 </Item> */
1580 if (uLoop == 2)
1581 {
1582 uint32_t cDisks = (uint32_t)stack.mapDisks.size();
1583 Utf8Str strDiskID = Utf8StrFmt("iso%RI32", ++cDisks);
1584 ++cDVDs;
1585 strDescription = "CD-ROM Drive";
1586 strCaption = Utf8StrFmt("cdrom%RI32", cDVDs); // OVFTool starts with 1
1587 type = ovf::ResourceType_CDDrive; // 15
1588 lAutomaticAllocation = 1;
1589
1590 //skip empty Medium. There are no information to add into section <References> or <DiskSection>
1591 if (desc.strVBoxCurrent.isNotEmpty() &&
1592 desc.skipIt == false)
1593 {
1594 // the following references the "<Disks>" XML block
1595 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
1596 }
1597
1598 // controller=<index>;channel=<c>
1599 size_t pos1 = desc.strExtraConfigCurrent.find("controller=");
1600 size_t pos2 = desc.strExtraConfigCurrent.find("channel=");
1601 int32_t lControllerIndex = -1;
1602 if (pos1 != Utf8Str::npos)
1603 {
1604 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
1605 if (lControllerIndex == lIDEPrimaryControllerIndex)
1606 ulParent = idIDEPrimaryController;
1607 else if (lControllerIndex == lIDESecondaryControllerIndex)
1608 ulParent = idIDESecondaryController;
1609 else if (lControllerIndex == lSCSIControllerIndex)
1610 ulParent = idSCSIController;
1611 else if (lControllerIndex == lSATAControllerIndex)
1612 ulParent = idSATAController;
1613 }
1614 if (pos2 != Utf8Str::npos)
1615 RTStrToInt32Ex(desc.strExtraConfigCurrent.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
1616
1617 LogFlowFunc(("DVD drive details: pos1=%d, pos2=%d, lControllerIndex=%d, lIDEPrimaryControllerIndex=%d, lIDESecondaryControllerIndex=%d, ulParent=%d, lAddressOnParent=%d\n",
1618 pos1, pos2, lControllerIndex, lIDEPrimaryControllerIndex,
1619 lIDESecondaryControllerIndex, ulParent, lAddressOnParent));
1620
1621 if ( !ulParent
1622 || lAddressOnParent == -1
1623 )
1624 throw setError(VBOX_E_NOT_SUPPORTED,
1625 tr("Missing or bad extra config string in DVD drive medium: \"%s\""),
1626 desc.strExtraConfigCurrent.c_str());
1627
1628 stack.mapDisks[strDiskID] = &desc;
1629
1630 //use the list stack.mapDiskSequence where the disks go as the "VirtualSystem" should be placed
1631 //in the OVF description file.
1632 stack.mapDiskSequence.push_back(strDiskID);
1633 stack.mapDiskSequenceForOneVM.push_back(strDiskID);
1634 // there is no DVD drive map to update because it is
1635 // handled completely with this entry.
1636 }
1637 break;
1638
1639 case VirtualSystemDescriptionType_NetworkAdapter:
1640 /* <Item>
1641 <rasd:AutomaticAllocation>true</rasd:AutomaticAllocation>
1642 <rasd:Caption>Ethernet adapter on 'VM Network'</rasd:Caption>
1643 <rasd:Connection>VM Network</rasd:Connection>
1644 <rasd:ElementName>VM network</rasd:ElementName>
1645 <rasd:InstanceID>3</rasd:InstanceID>
1646 <rasd:ResourceType>10</rasd:ResourceType>
1647 </Item> */
1648 if (uLoop == 2)
1649 {
1650 lAutomaticAllocation = 1;
1651 strCaption = Utf8StrFmt("Ethernet adapter on '%s'", desc.strOvf.c_str());
1652 type = ovf::ResourceType_EthernetAdapter; // 10
1653 /* Set the hardware type to something useful.
1654 * To be compatible with vmware & others we set
1655 * PCNet32 for our PCNet types & E1000 for the
1656 * E1000 cards. */
1657 switch (desc.strVBoxCurrent.toInt32())
1658 {
1659 case NetworkAdapterType_Am79C970A:
1660 case NetworkAdapterType_Am79C973: strResourceSubType = "PCNet32"; break;
1661#ifdef VBOX_WITH_E1000
1662 case NetworkAdapterType_I82540EM:
1663 case NetworkAdapterType_I82545EM:
1664 case NetworkAdapterType_I82543GC: strResourceSubType = "E1000"; break;
1665#endif /* VBOX_WITH_E1000 */
1666 }
1667 strConnection = desc.strOvf;
1668
1669 stack.mapNetworks[desc.strOvf] = true;
1670 }
1671 break;
1672
1673 case VirtualSystemDescriptionType_USBController:
1674 /* <Item ovf:required="false">
1675 <rasd:Caption>usb</rasd:Caption>
1676 <rasd:Description>USB Controller</rasd:Description>
1677 <rasd:InstanceId>3</rasd:InstanceId>
1678 <rasd:ResourceType>23</rasd:ResourceType>
1679 <rasd:Address>0</rasd:Address>
1680 <rasd:BusNumber>0</rasd:BusNumber>
1681 </Item> */
1682 if (uLoop == 1)
1683 {
1684 strDescription = "USB Controller";
1685 strCaption = "usb";
1686 type = ovf::ResourceType_USBController; // 23
1687 lAddress = 0; // this is what OVFTool writes
1688 lBusNumber = 0; // this is what OVFTool writes
1689 }
1690 break;
1691
1692 case VirtualSystemDescriptionType_SoundCard:
1693 /* <Item ovf:required="false">
1694 <rasd:Caption>sound</rasd:Caption>
1695 <rasd:Description>Sound Card</rasd:Description>
1696 <rasd:InstanceId>10</rasd:InstanceId>
1697 <rasd:ResourceType>35</rasd:ResourceType>
1698 <rasd:ResourceSubType>ensoniq1371</rasd:ResourceSubType>
1699 <rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
1700 <rasd:AddressOnParent>3</rasd:AddressOnParent>
1701 </Item> */
1702 if (uLoop == 1)
1703 {
1704 strDescription = "Sound Card";
1705 strCaption = "sound";
1706 type = ovf::ResourceType_SoundCard; // 35
1707 strResourceSubType = desc.strOvf; // e.g. ensoniq1371
1708 lAutomaticAllocation = 0;
1709 lAddressOnParent = 3; // what gives? this is what OVFTool writes
1710 }
1711 break;
1712
1713 default: break; /* Shut up MSC. */
1714 }
1715
1716 if (type)
1717 {
1718 xml::ElementNode *pItem;
1719 xml::ElementNode *pItemHelper;
1720 RTCString itemElement;
1721 RTCString itemElementHelper;
1722
1723 if (enFormat == ovf::OVFVersion_2_0)
1724 {
1725 if(uLoop == 2)
1726 {
1727 if (desc.type == VirtualSystemDescriptionType_NetworkAdapter)
1728 {
1729 itemElement = "epasd:";
1730 pItem = pelmVirtualHardwareSection->createChild("EthernetPortItem");
1731 }
1732 else if (desc.type == VirtualSystemDescriptionType_CDROM ||
1733 desc.type == VirtualSystemDescriptionType_HardDiskImage)
1734 {
1735 itemElement = "sasd:";
1736 pItem = pelmVirtualHardwareSection->createChild("StorageItem");
1737 }
1738 else
1739 pItem = NULL;
1740 }
1741 else
1742 {
1743 itemElement = "rasd:";
1744 pItem = pelmVirtualHardwareSection->createChild("Item");
1745 }
1746 }
1747 else
1748 {
1749 itemElement = "rasd:";
1750 pItem = pelmVirtualHardwareSection->createChild("Item");
1751 }
1752
1753 // NOTE: DO NOT CHANGE THE ORDER of these items! The OVF standards prescribes that
1754 // the elements from the rasd: namespace must be sorted by letter, and VMware
1755 // actually requires this as well (see public bug #6612)
1756
1757 if (lAddress != -1)
1758 {
1759 //pItem->createChild("rasd:Address")->addContent(Utf8StrFmt("%d", lAddress));
1760 itemElementHelper = itemElement;
1761 pItemHelper = pItem->createChild(itemElementHelper.append("Address").c_str());
1762 pItemHelper->addContent(Utf8StrFmt("%d", lAddress));
1763 }
1764
1765 if (lAddressOnParent != -1)
1766 {
1767 //pItem->createChild("rasd:AddressOnParent")->addContent(Utf8StrFmt("%d", lAddressOnParent));
1768 itemElementHelper = itemElement;
1769 pItemHelper = pItem->createChild(itemElementHelper.append("AddressOnParent").c_str());
1770 pItemHelper->addContent(Utf8StrFmt("%d", lAddressOnParent));
1771 }
1772
1773 if (!strAllocationUnits.isEmpty())
1774 {
1775 //pItem->createChild("rasd:AllocationUnits")->addContent(strAllocationUnits);
1776 itemElementHelper = itemElement;
1777 pItemHelper = pItem->createChild(itemElementHelper.append("AllocationUnits").c_str());
1778 pItemHelper->addContent(strAllocationUnits);
1779 }
1780
1781 if (lAutomaticAllocation != -1)
1782 {
1783 //pItem->createChild("rasd:AutomaticAllocation")->addContent( (lAutomaticAllocation) ? "true" : "false" );
1784 itemElementHelper = itemElement;
1785 pItemHelper = pItem->createChild(itemElementHelper.append("AutomaticAllocation").c_str());
1786 pItemHelper->addContent((lAutomaticAllocation) ? "true" : "false" );
1787 }
1788
1789 if (lBusNumber != -1)
1790 {
1791 if (enFormat == ovf::OVFVersion_0_9)
1792 {
1793 // BusNumber is invalid OVF 1.0 so only write it in 0.9 mode for OVFTool
1794 //pItem->createChild("rasd:BusNumber")->addContent(Utf8StrFmt("%d", lBusNumber));
1795 itemElementHelper = itemElement;
1796 pItemHelper = pItem->createChild(itemElementHelper.append("BusNumber").c_str());
1797 pItemHelper->addContent(Utf8StrFmt("%d", lBusNumber));
1798 }
1799 }
1800
1801 if (!strCaption.isEmpty())
1802 {
1803 //pItem->createChild("rasd:Caption")->addContent(strCaption);
1804 itemElementHelper = itemElement;
1805 pItemHelper = pItem->createChild(itemElementHelper.append("Caption").c_str());
1806 pItemHelper->addContent(strCaption);
1807 }
1808
1809 if (!strConnection.isEmpty())
1810 {
1811 //pItem->createChild("rasd:Connection")->addContent(strConnection);
1812 itemElementHelper = itemElement;
1813 pItemHelper = pItem->createChild(itemElementHelper.append("Connection").c_str());
1814 pItemHelper->addContent(strConnection);
1815 }
1816
1817 if (!strDescription.isEmpty())
1818 {
1819 //pItem->createChild("rasd:Description")->addContent(strDescription);
1820 itemElementHelper = itemElement;
1821 pItemHelper = pItem->createChild(itemElementHelper.append("Description").c_str());
1822 pItemHelper->addContent(strDescription);
1823 }
1824
1825 if (!strCaption.isEmpty())
1826 {
1827 if (enFormat == ovf::OVFVersion_1_0)
1828 {
1829 //pItem->createChild("rasd:ElementName")->addContent(strCaption);
1830 itemElementHelper = itemElement;
1831 pItemHelper = pItem->createChild(itemElementHelper.append("ElementName").c_str());
1832 pItemHelper->addContent(strCaption);
1833 }
1834 }
1835
1836 if (!strHostResource.isEmpty())
1837 {
1838 //pItem->createChild("rasd:HostResource")->addContent(strHostResource);
1839 itemElementHelper = itemElement;
1840 pItemHelper = pItem->createChild(itemElementHelper.append("HostResource").c_str());
1841 pItemHelper->addContent(strHostResource);
1842 }
1843
1844 {
1845 // <rasd:InstanceID>1</rasd:InstanceID>
1846 itemElementHelper = itemElement;
1847 if (enFormat == ovf::OVFVersion_0_9)
1848 //pelmInstanceID = pItem->createChild("rasd:InstanceId");
1849 pItemHelper = pItem->createChild(itemElementHelper.append("InstanceId").c_str());
1850 else
1851 //pelmInstanceID = pItem->createChild("rasd:InstanceID"); // capitalization changed...
1852 pItemHelper = pItem->createChild(itemElementHelper.append("InstanceID").c_str());
1853
1854 pItemHelper->addContent(Utf8StrFmt("%d", ulInstanceID++));
1855 }
1856
1857 if (ulParent)
1858 {
1859 //pItem->createChild("rasd:Parent")->addContent(Utf8StrFmt("%d", ulParent));
1860 itemElementHelper = itemElement;
1861 pItemHelper = pItem->createChild(itemElementHelper.append("Parent").c_str());
1862 pItemHelper->addContent(Utf8StrFmt("%d", ulParent));
1863 }
1864
1865 if (!strResourceSubType.isEmpty())
1866 {
1867 //pItem->createChild("rasd:ResourceSubType")->addContent(strResourceSubType);
1868 itemElementHelper = itemElement;
1869 pItemHelper = pItem->createChild(itemElementHelper.append("ResourceSubType").c_str());
1870 pItemHelper->addContent(strResourceSubType);
1871 }
1872
1873 {
1874 // <rasd:ResourceType>3</rasd:ResourceType>
1875 //pItem->createChild("rasd:ResourceType")->addContent(Utf8StrFmt("%d", type));
1876 itemElementHelper = itemElement;
1877 pItemHelper = pItem->createChild(itemElementHelper.append("ResourceType").c_str());
1878 pItemHelper->addContent(Utf8StrFmt("%d", type));
1879 }
1880
1881 // <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
1882 if (lVirtualQuantity != -1)
1883 {
1884 //pItem->createChild("rasd:VirtualQuantity")->addContent(Utf8StrFmt("%d", lVirtualQuantity));
1885 itemElementHelper = itemElement;
1886 pItemHelper = pItem->createChild(itemElementHelper.append("VirtualQuantity").c_str());
1887 pItemHelper->addContent(Utf8StrFmt("%d", lVirtualQuantity));
1888 }
1889 }
1890 }
1891 } // for (size_t uLoop = 1; uLoop <= 2; ++uLoop)
1892
1893 // now that we're done with the official OVF <Item> tags under <VirtualSystem>, write out VirtualBox XML
1894 // under the vbox: namespace
1895 xml::ElementNode *pelmVBoxMachine = pelmVirtualSystem->createChild("vbox:Machine");
1896 // ovf:required="false" tells other OVF parsers that they can ignore this thing
1897 pelmVBoxMachine->setAttribute("ovf:required", "false");
1898 // ovf:Info element is required or VMware will bail out on the vbox:Machine element
1899 pelmVBoxMachine->createChild("ovf:Info")->addContent("Complete VirtualBox machine configuration in VirtualBox format");
1900
1901 // create an empty machine config
1902 // use the same settings version as the current VM settings file
1903 settings::MachineConfigFile *pConfig = new settings::MachineConfigFile(&vsdescThis->m->pMachine->i_getSettingsFileFull());
1904
1905 writeLock.release();
1906 try
1907 {
1908 AutoWriteLock machineLock(vsdescThis->m->pMachine COMMA_LOCKVAL_SRC_POS);
1909 // fill the machine config
1910 vsdescThis->m->pMachine->i_copyMachineDataToSettings(*pConfig);
1911
1912 // Apply export tweaks to machine settings
1913 bool fStripAllMACs = m->optListExport.contains(ExportOptions_StripAllMACs);
1914 bool fStripAllNonNATMACs = m->optListExport.contains(ExportOptions_StripAllNonNATMACs);
1915 if (fStripAllMACs || fStripAllNonNATMACs)
1916 {
1917 for (settings::NetworkAdaptersList::iterator it = pConfig->hardwareMachine.llNetworkAdapters.begin();
1918 it != pConfig->hardwareMachine.llNetworkAdapters.end();
1919 ++it)
1920 {
1921 settings::NetworkAdapter &nic = *it;
1922 if (fStripAllMACs || (fStripAllNonNATMACs && nic.mode != NetworkAttachmentType_NAT))
1923 nic.strMACAddress.setNull();
1924 }
1925 }
1926
1927 // write the machine config to the vbox:Machine element
1928 pConfig->buildMachineXML(*pelmVBoxMachine,
1929 settings::MachineConfigFile::BuildMachineXML_WriteVBoxVersionAttribute
1930 /*| settings::MachineConfigFile::BuildMachineXML_SkipRemovableMedia*/
1931 | settings::MachineConfigFile::BuildMachineXML_SuppressSavedState,
1932 // but not BuildMachineXML_IncludeSnapshots nor BuildMachineXML_MediaRegistry
1933 pllElementsWithUuidAttributes);
1934 delete pConfig;
1935 }
1936 catch (...)
1937 {
1938 writeLock.acquire();
1939 delete pConfig;
1940 throw;
1941 }
1942 writeLock.acquire();
1943}
1944
1945/**
1946 * Actual worker code for writing out OVF/OVA to disk. This is called from Appliance::taskThreadWriteOVF()
1947 * and therefore runs on the OVF/OVA write worker thread.
1948 *
1949 * This runs in one context:
1950 *
1951 * 1) in a first worker thread; in that case, Appliance::Write() called Appliance::i_writeImpl();
1952 *
1953 * @param pTask
1954 * @return
1955 */
1956HRESULT Appliance::i_writeFS(TaskOVF *pTask)
1957{
1958 LogFlowFuncEnter();
1959 LogFlowFunc(("ENTER appliance %p\n", this));
1960
1961 AutoCaller autoCaller(this);
1962 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1963
1964 HRESULT rc = S_OK;
1965
1966 // Lock the media tree early to make sure nobody else tries to make changes
1967 // to the tree. Also lock the IAppliance object for writing.
1968 AutoMultiWriteLock2 multiLock(&mVirtualBox->i_getMediaTreeLockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
1969 // Additional protect the IAppliance object, cause we leave the lock
1970 // when starting the disk export and we don't won't block other
1971 // callers on this lengthy operations.
1972 m->state = Data::ApplianceExporting;
1973
1974 if (pTask->locInfo.strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
1975 rc = i_writeFSOVF(pTask, multiLock);
1976 else
1977 rc = i_writeFSOVA(pTask, multiLock);
1978
1979 // reset the state so others can call methods again
1980 m->state = Data::ApplianceIdle;
1981
1982 LogFlowFunc(("rc=%Rhrc\n", rc));
1983 LogFlowFuncLeave();
1984 return rc;
1985}
1986
1987HRESULT Appliance::i_writeFSOVF(TaskOVF *pTask, AutoWriteLockBase& writeLock)
1988{
1989 LogFlowFuncEnter();
1990
1991 HRESULT rc = S_OK;
1992
1993 PVDINTERFACEIO pShaIo = 0;
1994 PVDINTERFACEIO pFileIo = 0;
1995 do
1996 {
1997 pShaIo = ShaCreateInterface();
1998 if (!pShaIo)
1999 {
2000 rc = E_OUTOFMEMORY;
2001 break;
2002 }
2003 pFileIo = FileCreateInterface();
2004 if (!pFileIo)
2005 {
2006 rc = E_OUTOFMEMORY;
2007 break;
2008 }
2009
2010 SHASTORAGE storage;
2011 RT_ZERO(storage);
2012 storage.fCreateDigest = m->fManifest;
2013 storage.fSha256 = m->fSha256;
2014
2015
2016 Utf8Str name = i_applianceIOName(applianceIOFile);
2017
2018 int vrc = VDInterfaceAdd(&pFileIo->Core, name.c_str(),
2019 VDINTERFACETYPE_IO, 0, sizeof(VDINTERFACEIO),
2020 &storage.pVDImageIfaces);
2021 if (RT_FAILURE(vrc))
2022 {
2023 rc = E_FAIL;
2024 break;
2025 }
2026 rc = i_writeFSImpl(pTask, writeLock, pShaIo, &storage);
2027 } while (0);
2028
2029 /* Cleanup */
2030 if (pShaIo)
2031 RTMemFree(pShaIo);
2032 if (pFileIo)
2033 RTMemFree(pFileIo);
2034
2035 LogFlowFuncLeave();
2036 return rc;
2037}
2038
2039HRESULT Appliance::i_writeFSOVA(TaskOVF *pTask, AutoWriteLockBase& writeLock)
2040{
2041 LogFlowFuncEnter();
2042
2043 RTTAR tar;
2044 int vrc = RTTarOpen(&tar, pTask->locInfo.strPath.c_str(), RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_ALL);
2045 if (RT_FAILURE(vrc))
2046 return setError(VBOX_E_FILE_ERROR,
2047 tr("Could not create OVA file '%s' (%Rrc)"),
2048 pTask->locInfo.strPath.c_str(), vrc);
2049
2050 HRESULT rc = S_OK;
2051
2052 PVDINTERFACEIO pShaIo = 0;
2053 PVDINTERFACEIO pTarIo = 0;
2054 do
2055 {
2056 pShaIo = ShaCreateInterface();
2057 if (!pShaIo)
2058 {
2059 rc = E_OUTOFMEMORY;
2060 break;
2061 }
2062 pTarIo = tarWriterCreateInterface();
2063 if (!pTarIo)
2064 {
2065 rc = E_OUTOFMEMORY;
2066 break;
2067 }
2068 SHASTORAGE storage;
2069 RT_ZERO(storage);
2070 storage.fCreateDigest = m->fManifest;
2071 storage.fSha256 = m->fSha256;
2072
2073 Utf8Str name = i_applianceIOName(applianceIOTar);
2074
2075 vrc = VDInterfaceAdd(&pTarIo->Core, name.c_str(),
2076 VDINTERFACETYPE_IO, tar, sizeof(VDINTERFACEIO),
2077 &storage.pVDImageIfaces);
2078
2079 if (RT_FAILURE(vrc))
2080 {
2081 rc = E_FAIL;
2082 break;
2083 }
2084 rc = i_writeFSImpl(pTask, writeLock, pShaIo, &storage);
2085 } while (0);
2086
2087 RTTarClose(tar);
2088
2089 /* Cleanup */
2090 if (pShaIo)
2091 RTMemFree(pShaIo);
2092 if (pTarIo)
2093 RTMemFree(pTarIo);
2094
2095 /* Delete ova file on error */
2096 if (FAILED(rc))
2097 RTFileDelete(pTask->locInfo.strPath.c_str());
2098
2099 LogFlowFuncLeave();
2100 return rc;
2101}
2102
2103HRESULT Appliance::i_writeFSImpl(TaskOVF *pTask, AutoWriteLockBase& writeLock, PVDINTERFACEIO pIfIo, PSHASTORAGE pStorage)
2104{
2105 LogFlowFuncEnter();
2106
2107 HRESULT rc = S_OK;
2108
2109 list<STRPAIR> fileList;
2110 try
2111 {
2112 int vrc;
2113 // the XML stack contains two maps for disks and networks, which allows us to
2114 // a) have a list of unique disk names (to make sure the same disk name is only added once)
2115 // and b) keep a list of all networks
2116 XMLStack stack;
2117 // Scope this to free the memory as soon as this is finished
2118 {
2119 // Create a xml document
2120 xml::Document doc;
2121 // Now fully build a valid ovf document in memory
2122 i_buildXML(writeLock, doc, stack, pTask->locInfo.strPath, pTask->enFormat);
2123 /* Extract the OVA file name */
2124 Utf8Str strOvaFile = pTask->locInfo.strPath;
2125 /* Extract the path */
2126 Utf8Str strOvfFile = strOvaFile.stripSuffix().append(".ovf");
2127 // Create a memory buffer containing the XML. */
2128 void *pvBuf = 0;
2129 size_t cbSize;
2130 xml::XmlMemWriter writer;
2131 writer.write(doc, &pvBuf, &cbSize);
2132 if (RT_UNLIKELY(!pvBuf))
2133 throw setError(VBOX_E_FILE_ERROR,
2134 tr("Could not create OVF file '%s'"),
2135 strOvfFile.c_str());
2136 /* Write the ovf file to disk. */
2137 vrc = writeBufferToFile(strOvfFile.c_str(), pvBuf, cbSize, pIfIo, pStorage);
2138 if (RT_FAILURE(vrc))
2139 throw setError(VBOX_E_FILE_ERROR,
2140 tr("Could not create OVF file '%s' (%Rrc)"),
2141 strOvfFile.c_str(), vrc);
2142 fileList.push_back(STRPAIR(strOvfFile, pStorage->strDigest));
2143 }
2144
2145 // We need a proper format description
2146 ComObjPtr<MediumFormat> formatTemp;
2147
2148 ComObjPtr<MediumFormat> format;
2149 // Scope for the AutoReadLock
2150 {
2151 SystemProperties *pSysProps = mVirtualBox->i_getSystemProperties();
2152 AutoReadLock propsLock(pSysProps COMMA_LOCKVAL_SRC_POS);
2153 // We are always exporting to VMDK stream optimized for now
2154 formatTemp = pSysProps->i_mediumFormatFromExtension("iso");
2155
2156 format = pSysProps->i_mediumFormat("VMDK");
2157 if (format.isNull())
2158 throw setError(VBOX_E_NOT_SUPPORTED,
2159 tr("Invalid medium storage format"));
2160 }
2161
2162 // Finally, write out the disks!
2163 //use the list stack.mapDiskSequence where the disks were put as the "VirtualSystem"s had been placed
2164 //in the OVF description file. I.e. we have one "VirtualSystem" in the OVF file, we extract all disks
2165 //attached to it. And these disks are stored in the stack.mapDiskSequence. Next we shift to the next
2166 //"VirtualSystem" and repeat the operation.
2167 //And here we go through the list and extract all disks in the same sequence
2168 list<Utf8Str>::const_iterator itS;
2169 for (itS = stack.mapDiskSequence.begin();
2170 itS != stack.mapDiskSequence.end();
2171 ++itS)
2172 {
2173 const Utf8Str &strDiskID = *itS;
2174 const VirtualSystemDescriptionEntry *pDiskEntry = stack.mapDisks[strDiskID];
2175
2176 // source path: where the VBox image is
2177 const Utf8Str &strSrcFilePath = pDiskEntry->strVBoxCurrent;
2178
2179 //skip empty Medium. In common, It's may be empty CD/DVD
2180 if (strSrcFilePath.isEmpty() ||
2181 pDiskEntry->skipIt == true)
2182 continue;
2183
2184 // Do NOT check here whether the file exists. findHardDisk will
2185 // figure that out, and filesystem-based tests are simply wrong
2186 // in the general case (think of iSCSI).
2187
2188 // clone the disk:
2189 ComObjPtr<Medium> pSourceDisk;
2190
2191 Log(("Finding source disk \"%s\"\n", strSrcFilePath.c_str()));
2192
2193 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2194 {
2195 rc = mVirtualBox->i_findHardDiskByLocation(strSrcFilePath, true, &pSourceDisk);
2196 if (FAILED(rc)) throw rc;
2197 }
2198 else//may be CD or DVD
2199 {
2200 rc = mVirtualBox->i_findDVDOrFloppyImage(DeviceType_DVD,
2201 NULL,
2202 strSrcFilePath,
2203 true,
2204 &pSourceDisk);
2205 if (FAILED(rc)) throw rc;
2206 }
2207
2208 Bstr uuidSource;
2209 rc = pSourceDisk->COMGETTER(Id)(uuidSource.asOutParam());
2210 if (FAILED(rc)) throw rc;
2211 Guid guidSource(uuidSource);
2212
2213 // output filename
2214 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
2215 // target path needs to be composed from where the output OVF is
2216 Utf8Str strTargetFilePath(pTask->locInfo.strPath);
2217 strTargetFilePath.stripFilename()
2218 .append("/")
2219 .append(strTargetFileNameOnly);
2220
2221 // The exporting requests a lock on the media tree. So leave our lock temporary.
2222 writeLock.release();
2223 try
2224 {
2225 // advance to the next operation
2226 pTask->pProgress->SetNextOperation(BstrFmt(tr("Exporting to disk image '%s'"),
2227 RTPathFilename(strTargetFilePath.c_str())).raw(),
2228 pDiskEntry->ulSizeMB); // operation's weight, as set up
2229 // with the IProgress originally
2230
2231 // create a flat copy of the source disk image
2232 if (pDiskEntry->type == VirtualSystemDescriptionType_HardDiskImage)
2233 {
2234 ComObjPtr<Progress> pProgress2;
2235 pProgress2.createObject();
2236 rc = pProgress2->init(mVirtualBox, static_cast<IAppliance*>(this),
2237 BstrFmt(tr("Creating medium '%s'"),
2238 strTargetFilePath.c_str()).raw(), TRUE);
2239 if (FAILED(rc)) throw rc;
2240
2241 rc = pSourceDisk->i_exportFile(strTargetFilePath.c_str(),
2242 format,
2243 MediumVariant_VmdkStreamOptimized,
2244 m->m_pSecretKeyStore,
2245 pIfIo,
2246 pStorage,
2247 pProgress2);
2248 if (FAILED(rc)) throw rc;
2249
2250 ComPtr<IProgress> pProgress3(pProgress2);
2251 // now wait for the background disk operation to complete; this throws HRESULTs on error
2252 i_waitForAsyncProgress(pTask->pProgress, pProgress3);
2253 }
2254 else
2255 {
2256 //copy/clone CD/DVD image
2257 Assert(pDiskEntry->type == VirtualSystemDescriptionType_CDROM);
2258
2259 /* Read the ISO file and add one to OVA/OVF package */
2260 {
2261 void *pvStorage;
2262 RTFILE pFile = NULL;
2263 void *pvUser = pStorage;
2264
2265 vrc = pIfIo->pfnOpen(pvUser, strTargetFilePath.c_str(),
2266 RTFILE_O_OPEN_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_NONE,
2267 0,
2268 &pvStorage);
2269 if (RT_FAILURE(vrc))
2270 throw setError(VBOX_E_FILE_ERROR,
2271 tr("Could not create or open file '%s' (%Rrc)"),
2272 strTargetFilePath.c_str(), vrc);
2273
2274 vrc = RTFileOpen(&pFile,
2275 strSrcFilePath.c_str(),
2276 RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
2277
2278 if (RT_FAILURE(vrc) || pFile == NULL)
2279 {
2280 pIfIo->pfnClose(pvUser, pvStorage);
2281 throw setError(VBOX_E_FILE_ERROR,
2282 tr("Could not create or open file '%s' (%Rrc)"),
2283 strSrcFilePath.c_str(), vrc);
2284 }
2285
2286 uint64_t cbFile = 0;
2287 vrc = RTFileGetSize(pFile, &cbFile);
2288 if (RT_SUCCESS(vrc))
2289 {
2290 size_t const cbTmpSize = _1M;
2291 void *pvTmpBuf = RTMemAlloc(cbTmpSize);
2292 if (pvTmpBuf)
2293 {
2294 /* The copy loop. */
2295 uint64_t offDstFile = 0;
2296 for (;;)
2297 {
2298 size_t cbChunk = 0;
2299 vrc = RTFileRead(pFile, pvTmpBuf, cbTmpSize, &cbChunk);
2300 if (RT_FAILURE(vrc) || cbChunk == 0)
2301 break;
2302
2303 size_t cbWritten = 0;
2304 vrc = pIfIo->pfnWriteSync(pvUser,
2305 pvStorage,
2306 offDstFile,
2307 pvTmpBuf,
2308 cbChunk,
2309 &cbWritten);
2310 if (RT_FAILURE(vrc))
2311 break;
2312 Assert(cbWritten == cbChunk);
2313
2314 offDstFile += cbWritten;
2315 }
2316
2317 RTMemFree(pvTmpBuf);
2318 }
2319 else
2320 vrc = VERR_NO_MEMORY;
2321 }
2322
2323 pIfIo->pfnClose(pvUser, pvStorage);
2324 RTFileClose(pFile);
2325
2326 if (RT_FAILURE(vrc))
2327 {
2328 if (vrc == VERR_EOF)
2329 vrc = VINF_SUCCESS;
2330 else
2331 throw setError(VBOX_E_FILE_ERROR,
2332 tr("Error during copy CD/DVD image '%s' (%Rrc)"),
2333 strSrcFilePath.c_str(), vrc);
2334 }
2335 }
2336 }
2337 }
2338 catch (HRESULT rc3)
2339 {
2340 writeLock.acquire();
2341 /// @todo file deletion on error? If not, we can remove that whole try/catch block.
2342 throw rc3;
2343 }
2344 // Finished, lock again (so nobody mess around with the medium tree
2345 // in the meantime)
2346 writeLock.acquire();
2347 fileList.push_back(STRPAIR(strTargetFilePath, pStorage->strDigest));
2348 }
2349
2350 if (m->fManifest)
2351 {
2352 // Create & write the manifest file
2353 Utf8Str strMfFilePath = Utf8Str(pTask->locInfo.strPath).stripSuffix().append(".mf");
2354 Utf8Str strMfFileName = Utf8Str(strMfFilePath).stripPath();
2355 pTask->pProgress->SetNextOperation(BstrFmt(tr("Creating manifest file '%s'"), strMfFileName.c_str()).raw(),
2356 m->ulWeightForManifestOperation); // operation's weight, as set up
2357 // with the IProgress originally);
2358 PRTMANIFESTTEST paManifestFiles = (PRTMANIFESTTEST)RTMemAlloc(sizeof(RTMANIFESTTEST) * fileList.size());
2359 size_t i = 0;
2360 list<STRPAIR>::const_iterator it1;
2361 for (it1 = fileList.begin();
2362 it1 != fileList.end();
2363 ++it1, ++i)
2364 {
2365 paManifestFiles[i].pszTestFile = (*it1).first.c_str();
2366 paManifestFiles[i].pszTestDigest = (*it1).second.c_str();
2367 }
2368 void *pvBuf;
2369 size_t cbSize;
2370 vrc = RTManifestWriteFilesBuf(&pvBuf, &cbSize, m->fSha256 ? RTDIGESTTYPE_SHA256 : RTDIGESTTYPE_SHA1,
2371 paManifestFiles, fileList.size());
2372 RTMemFree(paManifestFiles);
2373 if (RT_FAILURE(vrc))
2374 throw setError(VBOX_E_FILE_ERROR,
2375 tr("Could not create manifest file '%s' (%Rrc)"),
2376 strMfFileName.c_str(), vrc);
2377 /* Disable digest creation for the manifest file. */
2378 pStorage->fCreateDigest = false;
2379 /* Write the manifest file to disk. */
2380 vrc = writeBufferToFile(strMfFilePath.c_str(), pvBuf, cbSize, pIfIo, pStorage);
2381 RTMemFree(pvBuf);
2382 if (RT_FAILURE(vrc))
2383 throw setError(VBOX_E_FILE_ERROR,
2384 tr("Could not create manifest file '%s' (%Rrc)"),
2385 strMfFilePath.c_str(), vrc);
2386 }
2387 }
2388 catch (RTCError &x) // includes all XML exceptions
2389 {
2390 rc = setError(VBOX_E_FILE_ERROR,
2391 x.what());
2392 }
2393 catch (HRESULT aRC)
2394 {
2395 rc = aRC;
2396 }
2397
2398 /* Cleanup on error */
2399 if (FAILED(rc))
2400 {
2401 list<STRPAIR>::const_iterator it1;
2402 for (it1 = fileList.begin();
2403 it1 != fileList.end();
2404 ++it1)
2405 pIfIo->pfnDelete(pStorage, (*it1).first.c_str());
2406 }
2407
2408 LogFlowFunc(("rc=%Rhrc\n", rc));
2409 LogFlowFuncLeave();
2410
2411 return rc;
2412}
2413
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