VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/MediumImpl.cpp@ 67232

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

Main/ApplianceExport/Medium: Added progress to i_addRawToFss.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 360.9 KB
Line 
1/* $Id: MediumImpl.cpp 67232 2017-06-02 11:28:48Z vboxsync $ */
2/** @file
3 * VirtualBox COM class implementation
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.215389.xyz. 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#include "MediumImpl.h"
18#include "TokenImpl.h"
19#include "ProgressImpl.h"
20#include "SystemPropertiesImpl.h"
21#include "VirtualBoxImpl.h"
22#include "ExtPackManagerImpl.h"
23
24#include "AutoCaller.h"
25#include "Logging.h"
26#include "ThreadTask.h"
27#include "VBox/com/MultiResult.h"
28#include "VBox/com/ErrorInfo.h"
29
30#include <VBox/err.h>
31#include <VBox/settings.h>
32
33#include <iprt/param.h>
34#include <iprt/path.h>
35#include <iprt/file.h>
36#include <iprt/tcp.h>
37#include <iprt/cpp/utils.h>
38#include <iprt/memsafer.h>
39#include <iprt/base64.h>
40
41#include <VBox/vd.h>
42
43#include <algorithm>
44#include <list>
45
46
47typedef std::list<Guid> GuidList;
48
49
50#ifdef VBOX_WITH_EXTPACK
51static const char g_szVDPlugin[] = "VDPluginCrypt";
52#endif
53
54
55////////////////////////////////////////////////////////////////////////////////
56//
57// Medium data definition
58//
59////////////////////////////////////////////////////////////////////////////////
60
61/** Describes how a machine refers to this medium. */
62struct BackRef
63{
64 /** Equality predicate for stdc++. */
65 struct EqualsTo : public std::unary_function <BackRef, bool>
66 {
67 explicit EqualsTo(const Guid &aMachineId) : machineId(aMachineId) {}
68
69 bool operator()(const argument_type &aThat) const
70 {
71 return aThat.machineId == machineId;
72 }
73
74 const Guid machineId;
75 };
76
77 BackRef(const Guid &aMachineId,
78 const Guid &aSnapshotId = Guid::Empty)
79 : machineId(aMachineId),
80 fInCurState(aSnapshotId.isZero())
81 {
82 if (aSnapshotId.isValid() && !aSnapshotId.isZero())
83 llSnapshotIds.push_back(aSnapshotId);
84 }
85
86 Guid machineId;
87 bool fInCurState : 1;
88 GuidList llSnapshotIds;
89};
90
91typedef std::list<BackRef> BackRefList;
92
93struct Medium::Data
94{
95 Data()
96 : pVirtualBox(NULL),
97 state(MediumState_NotCreated),
98 variant(MediumVariant_Standard),
99 size(0),
100 readers(0),
101 preLockState(MediumState_NotCreated),
102 queryInfoSem(LOCKCLASS_MEDIUMQUERY),
103 queryInfoRunning(false),
104 type(MediumType_Normal),
105 devType(DeviceType_HardDisk),
106 logicalSize(0),
107 hddOpenMode(OpenReadWrite),
108 autoReset(false),
109 hostDrive(false),
110 implicit(false),
111 fClosing(false),
112 uOpenFlagsDef(VD_OPEN_FLAGS_IGNORE_FLUSH),
113 numCreateDiffTasks(0),
114 vdDiskIfaces(NULL),
115 vdImageIfaces(NULL),
116 fMoveThisMedium(false)
117 { }
118
119 /** weak VirtualBox parent */
120 VirtualBox * const pVirtualBox;
121
122 // pParent and llChildren are protected by VirtualBox::i_getMediaTreeLockHandle()
123 ComObjPtr<Medium> pParent;
124 MediaList llChildren; // to add a child, just call push_back; to remove
125 // a child, call child->deparent() which does a lookup
126
127 GuidList llRegistryIDs; // media registries in which this medium is listed
128
129 const Guid id;
130 Utf8Str strDescription;
131 MediumState_T state;
132 MediumVariant_T variant;
133 Utf8Str strLocationFull;
134 uint64_t size;
135 Utf8Str strLastAccessError;
136
137 BackRefList backRefs;
138
139 size_t readers;
140 MediumState_T preLockState;
141
142 /** Special synchronization for operations which must wait for
143 * Medium::i_queryInfo in another thread to complete. Using a SemRW is
144 * not quite ideal, but at least it is subject to the lock validator,
145 * unlike the SemEventMulti which we had here for many years. Catching
146 * possible deadlocks is more important than a tiny bit of efficiency. */
147 RWLockHandle queryInfoSem;
148 bool queryInfoRunning : 1;
149
150 const Utf8Str strFormat;
151 ComObjPtr<MediumFormat> formatObj;
152
153 MediumType_T type;
154 DeviceType_T devType;
155 uint64_t logicalSize;
156
157 HDDOpenMode hddOpenMode;
158
159 bool autoReset : 1;
160
161 /** New UUID to be set on the next Medium::i_queryInfo call. */
162 const Guid uuidImage;
163 /** New parent UUID to be set on the next Medium::i_queryInfo call. */
164 const Guid uuidParentImage;
165
166 bool hostDrive : 1;
167
168 settings::StringsMap mapProperties;
169
170 bool implicit : 1;
171 /** Flag whether the medium is in the process of being closed. */
172 bool fClosing: 1;
173
174 /** Default flags passed to VDOpen(). */
175 unsigned uOpenFlagsDef;
176
177 uint32_t numCreateDiffTasks;
178
179 Utf8Str vdError; /*< Error remembered by the VD error callback. */
180
181 VDINTERFACEERROR vdIfError;
182
183 VDINTERFACECONFIG vdIfConfig;
184
185 VDINTERFACETCPNET vdIfTcpNet;
186
187 PVDINTERFACE vdDiskIfaces;
188 PVDINTERFACE vdImageIfaces;
189
190 /** Flag if the medium is going to move to a new
191 * location. */
192 bool fMoveThisMedium;
193 /** new location path */
194 Utf8Str strNewLocationFull;
195};
196
197typedef struct VDSOCKETINT
198{
199 /** Socket handle. */
200 RTSOCKET hSocket;
201} VDSOCKETINT, *PVDSOCKETINT;
202
203////////////////////////////////////////////////////////////////////////////////
204//
205// Globals
206//
207////////////////////////////////////////////////////////////////////////////////
208
209/**
210 * Medium::Task class for asynchronous operations.
211 *
212 * @note Instances of this class must be created using new() because the
213 * task thread function will delete them when the task is complete.
214 *
215 * @note The constructor of this class adds a caller on the managed Medium
216 * object which is automatically released upon destruction.
217 */
218class Medium::Task : public ThreadTask
219{
220public:
221 Task(Medium *aMedium, Progress *aProgress)
222 : ThreadTask("Medium::Task"),
223 mVDOperationIfaces(NULL),
224 mMedium(aMedium),
225 mMediumCaller(aMedium),
226 mProgress(aProgress),
227 mVirtualBoxCaller(NULL)
228 {
229 AssertReturnVoidStmt(aMedium, mRC = E_FAIL);
230 mRC = mMediumCaller.rc();
231 if (FAILED(mRC))
232 return;
233
234 /* Get strong VirtualBox reference, see below. */
235 VirtualBox *pVirtualBox = aMedium->m->pVirtualBox;
236 mVirtualBox = pVirtualBox;
237 mVirtualBoxCaller.attach(pVirtualBox);
238 mRC = mVirtualBoxCaller.rc();
239 if (FAILED(mRC))
240 return;
241
242 /* Set up a per-operation progress interface, can be used freely (for
243 * binary operations you can use it either on the source or target). */
244 mVDIfProgress.pfnProgress = vdProgressCall;
245 int vrc = VDInterfaceAdd(&mVDIfProgress.Core,
246 "Medium::Task::vdInterfaceProgress",
247 VDINTERFACETYPE_PROGRESS,
248 mProgress,
249 sizeof(VDINTERFACEPROGRESS),
250 &mVDOperationIfaces);
251 AssertRC(vrc);
252 if (RT_FAILURE(vrc))
253 mRC = E_FAIL;
254 }
255
256 // Make all destructors virtual. Just in case.
257 virtual ~Task()
258 {
259 /* send the notification of completion.*/
260 if ( isAsync()
261 && !mProgress.isNull())
262 mProgress->i_notifyComplete(mRC);
263 }
264
265 HRESULT rc() const { return mRC; }
266 bool isOk() const { return SUCCEEDED(rc()); }
267
268 const ComPtr<Progress>& GetProgressObject() const {return mProgress;}
269
270 /**
271 * Runs Medium::Task::executeTask() on the current thread
272 * instead of creating a new one.
273 */
274 HRESULT runNow()
275 {
276 LogFlowFuncEnter();
277
278 mRC = executeTask();
279
280 LogFlowFunc(("rc=%Rhrc\n", mRC));
281 LogFlowFuncLeave();
282 return mRC;
283 }
284
285 /**
286 * Implementation code for the "create base" task.
287 * Used as function for execution from a standalone thread.
288 */
289 void handler()
290 {
291 LogFlowFuncEnter();
292 try
293 {
294 mRC = executeTask(); /* (destructor picks up mRC, see above) */
295 LogFlowFunc(("rc=%Rhrc\n", mRC));
296 }
297 catch (...)
298 {
299 LogRel(("Some exception in the function Medium::Task:handler()\n"));
300 }
301
302 LogFlowFuncLeave();
303 }
304
305 PVDINTERFACE mVDOperationIfaces;
306
307 const ComObjPtr<Medium> mMedium;
308 AutoCaller mMediumCaller;
309
310protected:
311 HRESULT mRC;
312
313private:
314 virtual HRESULT executeTask() = 0;
315
316 const ComObjPtr<Progress> mProgress;
317
318 static DECLCALLBACK(int) vdProgressCall(void *pvUser, unsigned uPercent);
319
320 VDINTERFACEPROGRESS mVDIfProgress;
321
322 /* Must have a strong VirtualBox reference during a task otherwise the
323 * reference count might drop to 0 while a task is still running. This
324 * would result in weird behavior, including deadlocks due to uninit and
325 * locking order issues. The deadlock often is not detectable because the
326 * uninit uses event semaphores which sabotages deadlock detection. */
327 ComObjPtr<VirtualBox> mVirtualBox;
328 AutoCaller mVirtualBoxCaller;
329};
330
331HRESULT Medium::Task::executeTask()
332{
333 return E_NOTIMPL;//ReturnComNotImplemented()
334}
335
336class Medium::CreateBaseTask : public Medium::Task
337{
338public:
339 CreateBaseTask(Medium *aMedium,
340 Progress *aProgress,
341 uint64_t aSize,
342 MediumVariant_T aVariant)
343 : Medium::Task(aMedium, aProgress),
344 mSize(aSize),
345 mVariant(aVariant)
346 {
347 m_strTaskName = "createBase";
348 }
349
350 uint64_t mSize;
351 MediumVariant_T mVariant;
352
353private:
354 HRESULT executeTask();
355};
356
357class Medium::CreateDiffTask : public Medium::Task
358{
359public:
360 CreateDiffTask(Medium *aMedium,
361 Progress *aProgress,
362 Medium *aTarget,
363 MediumVariant_T aVariant,
364 MediumLockList *aMediumLockList,
365 bool fKeepMediumLockList = false)
366 : Medium::Task(aMedium, aProgress),
367 mpMediumLockList(aMediumLockList),
368 mTarget(aTarget),
369 mVariant(aVariant),
370 mTargetCaller(aTarget),
371 mfKeepMediumLockList(fKeepMediumLockList)
372 {
373 AssertReturnVoidStmt(aTarget != NULL, mRC = E_FAIL);
374 mRC = mTargetCaller.rc();
375 if (FAILED(mRC))
376 return;
377 m_strTaskName = "createDiff";
378 }
379
380 ~CreateDiffTask()
381 {
382 if (!mfKeepMediumLockList && mpMediumLockList)
383 delete mpMediumLockList;
384 }
385
386 MediumLockList *mpMediumLockList;
387
388 const ComObjPtr<Medium> mTarget;
389 MediumVariant_T mVariant;
390
391private:
392 HRESULT executeTask();
393 AutoCaller mTargetCaller;
394 bool mfKeepMediumLockList;
395};
396
397class Medium::CloneTask : public Medium::Task
398{
399public:
400 CloneTask(Medium *aMedium,
401 Progress *aProgress,
402 Medium *aTarget,
403 MediumVariant_T aVariant,
404 Medium *aParent,
405 uint32_t idxSrcImageSame,
406 uint32_t idxDstImageSame,
407 MediumLockList *aSourceMediumLockList,
408 MediumLockList *aTargetMediumLockList,
409 bool fKeepSourceMediumLockList = false,
410 bool fKeepTargetMediumLockList = false)
411 : Medium::Task(aMedium, aProgress),
412 mTarget(aTarget),
413 mParent(aParent),
414 mpSourceMediumLockList(aSourceMediumLockList),
415 mpTargetMediumLockList(aTargetMediumLockList),
416 mVariant(aVariant),
417 midxSrcImageSame(idxSrcImageSame),
418 midxDstImageSame(idxDstImageSame),
419 mTargetCaller(aTarget),
420 mParentCaller(aParent),
421 mfKeepSourceMediumLockList(fKeepSourceMediumLockList),
422 mfKeepTargetMediumLockList(fKeepTargetMediumLockList)
423 {
424 AssertReturnVoidStmt(aTarget != NULL, mRC = E_FAIL);
425 mRC = mTargetCaller.rc();
426 if (FAILED(mRC))
427 return;
428 /* aParent may be NULL */
429 mRC = mParentCaller.rc();
430 if (FAILED(mRC))
431 return;
432 AssertReturnVoidStmt(aSourceMediumLockList != NULL, mRC = E_FAIL);
433 AssertReturnVoidStmt(aTargetMediumLockList != NULL, mRC = E_FAIL);
434 m_strTaskName = "createClone";
435 }
436
437 ~CloneTask()
438 {
439 if (!mfKeepSourceMediumLockList && mpSourceMediumLockList)
440 delete mpSourceMediumLockList;
441 if (!mfKeepTargetMediumLockList && mpTargetMediumLockList)
442 delete mpTargetMediumLockList;
443 }
444
445 const ComObjPtr<Medium> mTarget;
446 const ComObjPtr<Medium> mParent;
447 MediumLockList *mpSourceMediumLockList;
448 MediumLockList *mpTargetMediumLockList;
449 MediumVariant_T mVariant;
450 uint32_t midxSrcImageSame;
451 uint32_t midxDstImageSame;
452
453private:
454 HRESULT executeTask();
455 AutoCaller mTargetCaller;
456 AutoCaller mParentCaller;
457 bool mfKeepSourceMediumLockList;
458 bool mfKeepTargetMediumLockList;
459};
460
461class Medium::MoveTask : public Medium::Task
462{
463public:
464 MoveTask(Medium *aMedium,
465 Progress *aProgress,
466 MediumVariant_T aVariant,
467 MediumLockList *aMediumLockList,
468 bool fKeepMediumLockList = false)
469 : Medium::Task(aMedium, aProgress),
470 mpMediumLockList(aMediumLockList),
471 mVariant(aVariant),
472 mfKeepMediumLockList(fKeepMediumLockList)
473 {
474 AssertReturnVoidStmt(aMediumLockList != NULL, mRC = E_FAIL);
475 m_strTaskName = "createMove";
476 }
477
478 ~MoveTask()
479 {
480 if (!mfKeepMediumLockList && mpMediumLockList)
481 delete mpMediumLockList;
482 }
483
484 MediumLockList *mpMediumLockList;
485 MediumVariant_T mVariant;
486
487private:
488 HRESULT executeTask();
489 bool mfKeepMediumLockList;
490};
491
492class Medium::CompactTask : public Medium::Task
493{
494public:
495 CompactTask(Medium *aMedium,
496 Progress *aProgress,
497 MediumLockList *aMediumLockList,
498 bool fKeepMediumLockList = false)
499 : Medium::Task(aMedium, aProgress),
500 mpMediumLockList(aMediumLockList),
501 mfKeepMediumLockList(fKeepMediumLockList)
502 {
503 AssertReturnVoidStmt(aMediumLockList != NULL, mRC = E_FAIL);
504 m_strTaskName = "createCompact";
505 }
506
507 ~CompactTask()
508 {
509 if (!mfKeepMediumLockList && mpMediumLockList)
510 delete mpMediumLockList;
511 }
512
513 MediumLockList *mpMediumLockList;
514
515private:
516 HRESULT executeTask();
517 bool mfKeepMediumLockList;
518};
519
520class Medium::ResizeTask : public Medium::Task
521{
522public:
523 ResizeTask(Medium *aMedium,
524 uint64_t aSize,
525 Progress *aProgress,
526 MediumLockList *aMediumLockList,
527 bool fKeepMediumLockList = false)
528 : Medium::Task(aMedium, aProgress),
529 mSize(aSize),
530 mpMediumLockList(aMediumLockList),
531 mfKeepMediumLockList(fKeepMediumLockList)
532 {
533 AssertReturnVoidStmt(aMediumLockList != NULL, mRC = E_FAIL);
534 m_strTaskName = "createResize";
535 }
536
537 ~ResizeTask()
538 {
539 if (!mfKeepMediumLockList && mpMediumLockList)
540 delete mpMediumLockList;
541 }
542
543 uint64_t mSize;
544 MediumLockList *mpMediumLockList;
545
546private:
547 HRESULT executeTask();
548 bool mfKeepMediumLockList;
549};
550
551class Medium::ResetTask : public Medium::Task
552{
553public:
554 ResetTask(Medium *aMedium,
555 Progress *aProgress,
556 MediumLockList *aMediumLockList,
557 bool fKeepMediumLockList = false)
558 : Medium::Task(aMedium, aProgress),
559 mpMediumLockList(aMediumLockList),
560 mfKeepMediumLockList(fKeepMediumLockList)
561 {
562 m_strTaskName = "createReset";
563 }
564
565 ~ResetTask()
566 {
567 if (!mfKeepMediumLockList && mpMediumLockList)
568 delete mpMediumLockList;
569 }
570
571 MediumLockList *mpMediumLockList;
572
573private:
574 HRESULT executeTask();
575 bool mfKeepMediumLockList;
576};
577
578class Medium::DeleteTask : public Medium::Task
579{
580public:
581 DeleteTask(Medium *aMedium,
582 Progress *aProgress,
583 MediumLockList *aMediumLockList,
584 bool fKeepMediumLockList = false)
585 : Medium::Task(aMedium, aProgress),
586 mpMediumLockList(aMediumLockList),
587 mfKeepMediumLockList(fKeepMediumLockList)
588 {
589 m_strTaskName = "createDelete";
590 }
591
592 ~DeleteTask()
593 {
594 if (!mfKeepMediumLockList && mpMediumLockList)
595 delete mpMediumLockList;
596 }
597
598 MediumLockList *mpMediumLockList;
599
600private:
601 HRESULT executeTask();
602 bool mfKeepMediumLockList;
603};
604
605class Medium::MergeTask : public Medium::Task
606{
607public:
608 MergeTask(Medium *aMedium,
609 Medium *aTarget,
610 bool fMergeForward,
611 Medium *aParentForTarget,
612 MediumLockList *aChildrenToReparent,
613 Progress *aProgress,
614 MediumLockList *aMediumLockList,
615 bool fKeepMediumLockList = false)
616 : Medium::Task(aMedium, aProgress),
617 mTarget(aTarget),
618 mfMergeForward(fMergeForward),
619 mParentForTarget(aParentForTarget),
620 mpChildrenToReparent(aChildrenToReparent),
621 mpMediumLockList(aMediumLockList),
622 mTargetCaller(aTarget),
623 mParentForTargetCaller(aParentForTarget),
624 mfKeepMediumLockList(fKeepMediumLockList)
625 {
626 AssertReturnVoidStmt(aMediumLockList != NULL, mRC = E_FAIL);
627 m_strTaskName = "createMerge";
628 }
629
630 ~MergeTask()
631 {
632 if (!mfKeepMediumLockList && mpMediumLockList)
633 delete mpMediumLockList;
634 if (mpChildrenToReparent)
635 delete mpChildrenToReparent;
636 }
637
638 const ComObjPtr<Medium> mTarget;
639 bool mfMergeForward;
640 /* When mpChildrenToReparent is null then mParentForTarget is non-null and
641 * vice versa. In other words: they are used in different cases. */
642 const ComObjPtr<Medium> mParentForTarget;
643 MediumLockList *mpChildrenToReparent;
644 MediumLockList *mpMediumLockList;
645
646private:
647 HRESULT executeTask();
648 AutoCaller mTargetCaller;
649 AutoCaller mParentForTargetCaller;
650 bool mfKeepMediumLockList;
651};
652
653class Medium::ExportTask : public Medium::Task
654{
655public:
656 ExportTask(Medium *aMedium,
657 Progress *aProgress,
658 const char *aFilename,
659 MediumFormat *aFormat,
660 MediumVariant_T aVariant,
661 SecretKeyStore *pSecretKeyStore,
662#ifdef VBOX_WITH_NEW_TAR_CREATOR
663 RTVFSIOSTREAM aVfsIosDst,
664#else
665 VDINTERFACEIO *aVDImageIOIf,
666 void *aVDImageIOUser,
667#endif
668 MediumLockList *aSourceMediumLockList,
669 bool fKeepSourceMediumLockList = false)
670 : Medium::Task(aMedium, aProgress),
671 mpSourceMediumLockList(aSourceMediumLockList),
672 mFilename(aFilename),
673 mFormat(aFormat),
674 mVariant(aVariant),
675 m_pSecretKeyStore(pSecretKeyStore),
676 mfKeepSourceMediumLockList(fKeepSourceMediumLockList)
677 {
678 AssertReturnVoidStmt(aSourceMediumLockList != NULL, mRC = E_FAIL);
679
680 mVDImageIfaces = aMedium->m->vdImageIfaces;
681
682#ifdef VBOX_WITH_NEW_TAR_CREATOR
683 int vrc = VDIfCreateFromVfsStream(aVfsIosDst, RTFILE_O_WRITE, &mpVfsIoIf);
684 AssertRCReturnVoidStmt(vrc, mRC = E_FAIL);
685
686 vrc = VDInterfaceAdd(&mpVfsIoIf->Core, "Medium::ExportTaskVfsIos",
687 VDINTERFACETYPE_IO, mpVfsIoIf,
688 sizeof(VDINTERFACEIO), &mVDImageIfaces);
689 AssertRCReturnVoidStmt(vrc, mRC = E_FAIL);
690#else
691
692 if (aVDImageIOIf)
693 {
694 int vrc = VDInterfaceAdd(&aVDImageIOIf->Core, "Medium::vdInterfaceIO",
695 VDINTERFACETYPE_IO, aVDImageIOUser,
696 sizeof(VDINTERFACEIO), &mVDImageIfaces);
697 AssertRCReturnVoidStmt(vrc, mRC = E_FAIL);
698 }
699#endif
700 m_strTaskName = "createExport";
701 }
702
703 ~ExportTask()
704 {
705 if (!mfKeepSourceMediumLockList && mpSourceMediumLockList)
706 delete mpSourceMediumLockList;
707#ifdef VBOX_WITH_NEW_TAR_CREATOR
708 if (mpVfsIoIf)
709 {
710 VDIfDestroyFromVfsStream(mpVfsIoIf);
711 mpVfsIoIf = NULL;
712 }
713#endif
714 }
715
716 MediumLockList *mpSourceMediumLockList;
717 Utf8Str mFilename;
718 ComObjPtr<MediumFormat> mFormat;
719 MediumVariant_T mVariant;
720 PVDINTERFACE mVDImageIfaces;
721 PVDINTERFACEIO mpVfsIoIf; /**< Pointer to the VFS I/O stream to VD I/O interface wrapper. */
722 SecretKeyStore *m_pSecretKeyStore;
723
724private:
725 HRESULT executeTask();
726 bool mfKeepSourceMediumLockList;
727};
728
729class Medium::ImportTask : public Medium::Task
730{
731public:
732 ImportTask(Medium *aMedium,
733 Progress *aProgress,
734 const char *aFilename,
735 MediumFormat *aFormat,
736 MediumVariant_T aVariant,
737 RTVFSIOSTREAM aVfsIosSrc,
738 Medium *aParent,
739 MediumLockList *aTargetMediumLockList,
740 bool fKeepTargetMediumLockList = false)
741 : Medium::Task(aMedium, aProgress),
742 mFilename(aFilename),
743 mFormat(aFormat),
744 mVariant(aVariant),
745 mParent(aParent),
746 mpTargetMediumLockList(aTargetMediumLockList),
747 mpVfsIoIf(NULL),
748 mParentCaller(aParent),
749 mfKeepTargetMediumLockList(fKeepTargetMediumLockList)
750 {
751 AssertReturnVoidStmt(aTargetMediumLockList != NULL, mRC = E_FAIL);
752 /* aParent may be NULL */
753 mRC = mParentCaller.rc();
754 if (FAILED(mRC))
755 return;
756
757 mVDImageIfaces = aMedium->m->vdImageIfaces;
758
759 int vrc = VDIfCreateFromVfsStream(aVfsIosSrc, RTFILE_O_READ, &mpVfsIoIf);
760 AssertRCReturnVoidStmt(vrc, mRC = E_FAIL);
761
762 vrc = VDInterfaceAdd(&mpVfsIoIf->Core, "Medium::ImportTaskVfsIos",
763 VDINTERFACETYPE_IO, mpVfsIoIf,
764 sizeof(VDINTERFACEIO), &mVDImageIfaces);
765 AssertRCReturnVoidStmt(vrc, mRC = E_FAIL);
766 m_strTaskName = "createImport";
767 }
768
769 ~ImportTask()
770 {
771 if (!mfKeepTargetMediumLockList && mpTargetMediumLockList)
772 delete mpTargetMediumLockList;
773 if (mpVfsIoIf)
774 {
775 VDIfDestroyFromVfsStream(mpVfsIoIf);
776 mpVfsIoIf = NULL;
777 }
778 }
779
780 Utf8Str mFilename;
781 ComObjPtr<MediumFormat> mFormat;
782 MediumVariant_T mVariant;
783 const ComObjPtr<Medium> mParent;
784 MediumLockList *mpTargetMediumLockList;
785 PVDINTERFACE mVDImageIfaces;
786 PVDINTERFACEIO mpVfsIoIf; /**< Pointer to the VFS I/O stream to VD I/O interface wrapper. */
787
788private:
789 HRESULT executeTask();
790 AutoCaller mParentCaller;
791 bool mfKeepTargetMediumLockList;
792};
793
794class Medium::EncryptTask : public Medium::Task
795{
796public:
797 EncryptTask(Medium *aMedium,
798 const com::Utf8Str &strNewPassword,
799 const com::Utf8Str &strCurrentPassword,
800 const com::Utf8Str &strCipher,
801 const com::Utf8Str &strNewPasswordId,
802 Progress *aProgress,
803 MediumLockList *aMediumLockList)
804 : Medium::Task(aMedium, aProgress),
805 mstrNewPassword(strNewPassword),
806 mstrCurrentPassword(strCurrentPassword),
807 mstrCipher(strCipher),
808 mstrNewPasswordId(strNewPasswordId),
809 mpMediumLockList(aMediumLockList)
810 {
811 AssertReturnVoidStmt(aMediumLockList != NULL, mRC = E_FAIL);
812 /* aParent may be NULL */
813 mRC = mParentCaller.rc();
814 if (FAILED(mRC))
815 return;
816
817 mVDImageIfaces = aMedium->m->vdImageIfaces;
818 m_strTaskName = "createEncrypt";
819 }
820
821 ~EncryptTask()
822 {
823 if (mstrNewPassword.length())
824 RTMemWipeThoroughly(mstrNewPassword.mutableRaw(), mstrNewPassword.length(), 10 /* cPasses */);
825 if (mstrCurrentPassword.length())
826 RTMemWipeThoroughly(mstrCurrentPassword.mutableRaw(), mstrCurrentPassword.length(), 10 /* cPasses */);
827
828 /* Keep any errors which might be set when deleting the lock list. */
829 ErrorInfoKeeper eik;
830 delete mpMediumLockList;
831 }
832
833 Utf8Str mstrNewPassword;
834 Utf8Str mstrCurrentPassword;
835 Utf8Str mstrCipher;
836 Utf8Str mstrNewPasswordId;
837 MediumLockList *mpMediumLockList;
838 PVDINTERFACE mVDImageIfaces;
839
840private:
841 HRESULT executeTask();
842 AutoCaller mParentCaller;
843};
844
845/**
846 * Settings for a crypto filter instance.
847 */
848struct Medium::CryptoFilterSettings
849{
850 CryptoFilterSettings()
851 : fCreateKeyStore(false),
852 pszPassword(NULL),
853 pszKeyStore(NULL),
854 pszKeyStoreLoad(NULL),
855 pbDek(NULL),
856 cbDek(0),
857 pszCipher(NULL),
858 pszCipherReturned(NULL)
859 { }
860
861 bool fCreateKeyStore;
862 const char *pszPassword;
863 char *pszKeyStore;
864 const char *pszKeyStoreLoad;
865
866 const uint8_t *pbDek;
867 size_t cbDek;
868 const char *pszCipher;
869
870 /** The cipher returned by the crypto filter. */
871 char *pszCipherReturned;
872
873 PVDINTERFACE vdFilterIfaces;
874
875 VDINTERFACECONFIG vdIfCfg;
876 VDINTERFACECRYPTO vdIfCrypto;
877};
878
879/**
880 * PFNVDPROGRESS callback handler for Task operations.
881 *
882 * @param pvUser Pointer to the Progress instance.
883 * @param uPercent Completion percentage (0-100).
884 */
885/*static*/
886DECLCALLBACK(int) Medium::Task::vdProgressCall(void *pvUser, unsigned uPercent)
887{
888 Progress *that = static_cast<Progress *>(pvUser);
889
890 if (that != NULL)
891 {
892 /* update the progress object, capping it at 99% as the final percent
893 * is used for additional operations like setting the UUIDs and similar. */
894 HRESULT rc = that->SetCurrentOperationProgress(uPercent * 99 / 100);
895 if (FAILED(rc))
896 {
897 if (rc == E_FAIL)
898 return VERR_CANCELLED;
899 else
900 return VERR_INVALID_STATE;
901 }
902 }
903
904 return VINF_SUCCESS;
905}
906
907/**
908 * Implementation code for the "create base" task.
909 */
910HRESULT Medium::CreateBaseTask::executeTask()
911{
912 return mMedium->i_taskCreateBaseHandler(*this);
913}
914
915/**
916 * Implementation code for the "create diff" task.
917 */
918HRESULT Medium::CreateDiffTask::executeTask()
919{
920 return mMedium->i_taskCreateDiffHandler(*this);
921}
922
923/**
924 * Implementation code for the "clone" task.
925 */
926HRESULT Medium::CloneTask::executeTask()
927{
928 return mMedium->i_taskCloneHandler(*this);
929}
930
931/**
932 * Implementation code for the "move" task.
933 */
934HRESULT Medium::MoveTask::executeTask()
935{
936 return mMedium->i_taskMoveHandler(*this);
937}
938
939/**
940 * Implementation code for the "compact" task.
941 */
942HRESULT Medium::CompactTask::executeTask()
943{
944 return mMedium->i_taskCompactHandler(*this);
945}
946
947/**
948 * Implementation code for the "resize" task.
949 */
950HRESULT Medium::ResizeTask::executeTask()
951{
952 return mMedium->i_taskResizeHandler(*this);
953}
954
955
956/**
957 * Implementation code for the "reset" task.
958 */
959HRESULT Medium::ResetTask::executeTask()
960{
961 return mMedium->i_taskResetHandler(*this);
962}
963
964/**
965 * Implementation code for the "delete" task.
966 */
967HRESULT Medium::DeleteTask::executeTask()
968{
969 return mMedium->i_taskDeleteHandler(*this);
970}
971
972/**
973 * Implementation code for the "merge" task.
974 */
975HRESULT Medium::MergeTask::executeTask()
976{
977 return mMedium->i_taskMergeHandler(*this);
978}
979
980/**
981 * Implementation code for the "export" task.
982 */
983HRESULT Medium::ExportTask::executeTask()
984{
985 return mMedium->i_taskExportHandler(*this);
986}
987
988/**
989 * Implementation code for the "import" task.
990 */
991HRESULT Medium::ImportTask::executeTask()
992{
993 return mMedium->i_taskImportHandler(*this);
994}
995
996/**
997 * Implementation code for the "encrypt" task.
998 */
999HRESULT Medium::EncryptTask::executeTask()
1000{
1001 return mMedium->i_taskEncryptHandler(*this);
1002}
1003
1004////////////////////////////////////////////////////////////////////////////////
1005//
1006// Medium constructor / destructor
1007//
1008////////////////////////////////////////////////////////////////////////////////
1009
1010DEFINE_EMPTY_CTOR_DTOR(Medium)
1011
1012HRESULT Medium::FinalConstruct()
1013{
1014 m = new Data;
1015
1016 /* Initialize the callbacks of the VD error interface */
1017 m->vdIfError.pfnError = i_vdErrorCall;
1018 m->vdIfError.pfnMessage = NULL;
1019
1020 /* Initialize the callbacks of the VD config interface */
1021 m->vdIfConfig.pfnAreKeysValid = i_vdConfigAreKeysValid;
1022 m->vdIfConfig.pfnQuerySize = i_vdConfigQuerySize;
1023 m->vdIfConfig.pfnQuery = i_vdConfigQuery;
1024 m->vdIfConfig.pfnQueryBytes = NULL;
1025
1026 /* Initialize the callbacks of the VD TCP interface (we always use the host
1027 * IP stack for now) */
1028 m->vdIfTcpNet.pfnSocketCreate = i_vdTcpSocketCreate;
1029 m->vdIfTcpNet.pfnSocketDestroy = i_vdTcpSocketDestroy;
1030 m->vdIfTcpNet.pfnClientConnect = i_vdTcpClientConnect;
1031 m->vdIfTcpNet.pfnClientClose = i_vdTcpClientClose;
1032 m->vdIfTcpNet.pfnIsClientConnected = i_vdTcpIsClientConnected;
1033 m->vdIfTcpNet.pfnSelectOne = i_vdTcpSelectOne;
1034 m->vdIfTcpNet.pfnRead = i_vdTcpRead;
1035 m->vdIfTcpNet.pfnWrite = i_vdTcpWrite;
1036 m->vdIfTcpNet.pfnSgWrite = i_vdTcpSgWrite;
1037 m->vdIfTcpNet.pfnFlush = i_vdTcpFlush;
1038 m->vdIfTcpNet.pfnSetSendCoalescing = i_vdTcpSetSendCoalescing;
1039 m->vdIfTcpNet.pfnGetLocalAddress = i_vdTcpGetLocalAddress;
1040 m->vdIfTcpNet.pfnGetPeerAddress = i_vdTcpGetPeerAddress;
1041 m->vdIfTcpNet.pfnSelectOneEx = NULL;
1042 m->vdIfTcpNet.pfnPoke = NULL;
1043
1044 /* Initialize the per-disk interface chain (could be done more globally,
1045 * but it's not wasting much time or space so it's not worth it). */
1046 int vrc;
1047 vrc = VDInterfaceAdd(&m->vdIfError.Core,
1048 "Medium::vdInterfaceError",
1049 VDINTERFACETYPE_ERROR, this,
1050 sizeof(VDINTERFACEERROR), &m->vdDiskIfaces);
1051 AssertRCReturn(vrc, E_FAIL);
1052
1053 /* Initialize the per-image interface chain */
1054 vrc = VDInterfaceAdd(&m->vdIfConfig.Core,
1055 "Medium::vdInterfaceConfig",
1056 VDINTERFACETYPE_CONFIG, this,
1057 sizeof(VDINTERFACECONFIG), &m->vdImageIfaces);
1058 AssertRCReturn(vrc, E_FAIL);
1059
1060 vrc = VDInterfaceAdd(&m->vdIfTcpNet.Core,
1061 "Medium::vdInterfaceTcpNet",
1062 VDINTERFACETYPE_TCPNET, this,
1063 sizeof(VDINTERFACETCPNET), &m->vdImageIfaces);
1064 AssertRCReturn(vrc, E_FAIL);
1065
1066 return BaseFinalConstruct();
1067}
1068
1069void Medium::FinalRelease()
1070{
1071 uninit();
1072
1073 delete m;
1074
1075 BaseFinalRelease();
1076}
1077
1078/**
1079 * Initializes an empty hard disk object without creating or opening an associated
1080 * storage unit.
1081 *
1082 * This gets called by VirtualBox::CreateMedium() in which case uuidMachineRegistry
1083 * is empty since starting with VirtualBox 4.0, we no longer add opened media to a
1084 * registry automatically (this is deferred until the medium is attached to a machine).
1085 *
1086 * This also gets called when VirtualBox creates diff images; in this case uuidMachineRegistry
1087 * is set to the registry of the parent image to make sure they all end up in the same
1088 * file.
1089 *
1090 * For hard disks that don't have the MediumFormatCapabilities_CreateFixed or
1091 * MediumFormatCapabilities_CreateDynamic capability (and therefore cannot be created or deleted
1092 * with the means of VirtualBox) the associated storage unit is assumed to be
1093 * ready for use so the state of the hard disk object will be set to Created.
1094 *
1095 * @param aVirtualBox VirtualBox object.
1096 * @param aFormat
1097 * @param aLocation Storage unit location.
1098 * @param uuidMachineRegistry The registry to which this medium should be added
1099 * (global registry UUID or machine UUID or empty if none).
1100 * @param aDeviceType Device Type.
1101 */
1102HRESULT Medium::init(VirtualBox *aVirtualBox,
1103 const Utf8Str &aFormat,
1104 const Utf8Str &aLocation,
1105 const Guid &uuidMachineRegistry,
1106 const DeviceType_T aDeviceType)
1107{
1108 AssertReturn(aVirtualBox != NULL, E_FAIL);
1109 AssertReturn(!aFormat.isEmpty(), E_FAIL);
1110
1111 /* Enclose the state transition NotReady->InInit->Ready */
1112 AutoInitSpan autoInitSpan(this);
1113 AssertReturn(autoInitSpan.isOk(), E_FAIL);
1114
1115 HRESULT rc = S_OK;
1116
1117 unconst(m->pVirtualBox) = aVirtualBox;
1118
1119 if (uuidMachineRegistry.isValid() && !uuidMachineRegistry.isZero())
1120 m->llRegistryIDs.push_back(uuidMachineRegistry);
1121
1122 /* no storage yet */
1123 m->state = MediumState_NotCreated;
1124
1125 /* cannot be a host drive */
1126 m->hostDrive = false;
1127
1128 m->devType = aDeviceType;
1129
1130 /* No storage unit is created yet, no need to call Medium::i_queryInfo */
1131
1132 rc = i_setFormat(aFormat);
1133 if (FAILED(rc)) return rc;
1134
1135 rc = i_setLocation(aLocation);
1136 if (FAILED(rc)) return rc;
1137
1138 if (!(m->formatObj->i_getCapabilities() & ( MediumFormatCapabilities_CreateFixed
1139 | MediumFormatCapabilities_CreateDynamic))
1140 )
1141 {
1142 /* Storage for mediums of this format can neither be explicitly
1143 * created by VirtualBox nor deleted, so we place the medium to
1144 * Inaccessible state here and also add it to the registry. The
1145 * state means that one has to use RefreshState() to update the
1146 * medium format specific fields. */
1147 m->state = MediumState_Inaccessible;
1148 // create new UUID
1149 unconst(m->id).create();
1150
1151 AutoWriteLock treeLock(m->pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1152 ComObjPtr<Medium> pMedium;
1153
1154 /*
1155 * Check whether the UUID is taken already and create a new one
1156 * if required.
1157 * Try this only a limited amount of times in case the PRNG is broken
1158 * in some way to prevent an endless loop.
1159 */
1160 for (unsigned i = 0; i < 5; i++)
1161 {
1162 bool fInUse;
1163
1164 fInUse = m->pVirtualBox->i_isMediaUuidInUse(m->id, aDeviceType);
1165 if (fInUse)
1166 {
1167 // create new UUID
1168 unconst(m->id).create();
1169 }
1170 else
1171 break;
1172 }
1173
1174 rc = m->pVirtualBox->i_registerMedium(this, &pMedium, treeLock);
1175 Assert(this == pMedium || FAILED(rc));
1176 }
1177
1178 /* Confirm a successful initialization when it's the case */
1179 if (SUCCEEDED(rc))
1180 autoInitSpan.setSucceeded();
1181
1182 return rc;
1183}
1184
1185/**
1186 * Initializes the medium object by opening the storage unit at the specified
1187 * location. The enOpenMode parameter defines whether the medium will be opened
1188 * read/write or read-only.
1189 *
1190 * This gets called by VirtualBox::OpenMedium() and also by
1191 * Machine::AttachDevice() and createImplicitDiffs() when new diff
1192 * images are created.
1193 *
1194 * There is no registry for this case since starting with VirtualBox 4.0, we
1195 * no longer add opened media to a registry automatically (this is deferred
1196 * until the medium is attached to a machine).
1197 *
1198 * For hard disks, the UUID, format and the parent of this medium will be
1199 * determined when reading the medium storage unit. For DVD and floppy images,
1200 * which have no UUIDs in their storage units, new UUIDs are created.
1201 * If the detected or set parent is not known to VirtualBox, then this method
1202 * will fail.
1203 *
1204 * @param aVirtualBox VirtualBox object.
1205 * @param aLocation Storage unit location.
1206 * @param enOpenMode Whether to open the medium read/write or read-only.
1207 * @param fForceNewUuid Whether a new UUID should be set to avoid duplicates.
1208 * @param aDeviceType Device type of medium.
1209 */
1210HRESULT Medium::init(VirtualBox *aVirtualBox,
1211 const Utf8Str &aLocation,
1212 HDDOpenMode enOpenMode,
1213 bool fForceNewUuid,
1214 DeviceType_T aDeviceType)
1215{
1216 AssertReturn(aVirtualBox, E_INVALIDARG);
1217 AssertReturn(!aLocation.isEmpty(), E_INVALIDARG);
1218
1219 HRESULT rc = S_OK;
1220
1221 {
1222 /* Enclose the state transition NotReady->InInit->Ready */
1223 AutoInitSpan autoInitSpan(this);
1224 AssertReturn(autoInitSpan.isOk(), E_FAIL);
1225
1226 unconst(m->pVirtualBox) = aVirtualBox;
1227
1228 /* there must be a storage unit */
1229 m->state = MediumState_Created;
1230
1231 /* remember device type for correct unregistering later */
1232 m->devType = aDeviceType;
1233
1234 /* cannot be a host drive */
1235 m->hostDrive = false;
1236
1237 /* remember the open mode (defaults to ReadWrite) */
1238 m->hddOpenMode = enOpenMode;
1239
1240 if (aDeviceType == DeviceType_DVD)
1241 m->type = MediumType_Readonly;
1242 else if (aDeviceType == DeviceType_Floppy)
1243 m->type = MediumType_Writethrough;
1244
1245 rc = i_setLocation(aLocation);
1246 if (FAILED(rc)) return rc;
1247
1248 /* get all the information about the medium from the storage unit */
1249 if (fForceNewUuid)
1250 unconst(m->uuidImage).create();
1251
1252 m->state = MediumState_Inaccessible;
1253 m->strLastAccessError = tr("Accessibility check was not yet performed");
1254
1255 /* Confirm a successful initialization before the call to i_queryInfo.
1256 * Otherwise we can end up with a AutoCaller deadlock because the
1257 * medium becomes visible but is not marked as initialized. Causes
1258 * locking trouble (e.g. trying to save media registries) which is
1259 * hard to solve. */
1260 autoInitSpan.setSucceeded();
1261 }
1262
1263 /* we're normal code from now on, no longer init */
1264 AutoCaller autoCaller(this);
1265 if (FAILED(autoCaller.rc()))
1266 return autoCaller.rc();
1267
1268 /* need to call i_queryInfo immediately to correctly place the medium in
1269 * the respective media tree and update other information such as uuid */
1270 rc = i_queryInfo(fForceNewUuid /* fSetImageId */, false /* fSetParentId */,
1271 autoCaller);
1272 if (SUCCEEDED(rc))
1273 {
1274 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1275
1276 /* if the storage unit is not accessible, it's not acceptable for the
1277 * newly opened media so convert this into an error */
1278 if (m->state == MediumState_Inaccessible)
1279 {
1280 Assert(!m->strLastAccessError.isEmpty());
1281 rc = setError(E_FAIL, "%s", m->strLastAccessError.c_str());
1282 alock.release();
1283 autoCaller.release();
1284 uninit();
1285 }
1286 else
1287 {
1288 AssertStmt(!m->id.isZero(),
1289 alock.release(); autoCaller.release(); uninit(); return E_FAIL);
1290
1291 /* storage format must be detected by Medium::i_queryInfo if the
1292 * medium is accessible */
1293 AssertStmt(!m->strFormat.isEmpty(),
1294 alock.release(); autoCaller.release(); uninit(); return E_FAIL);
1295 }
1296 }
1297 else
1298 {
1299 /* opening this image failed, mark the object as dead */
1300 autoCaller.release();
1301 uninit();
1302 }
1303
1304 return rc;
1305}
1306
1307/**
1308 * Initializes the medium object by loading its data from the given settings
1309 * node. The medium will always be opened read/write.
1310 *
1311 * In this case, since we're loading from a registry, uuidMachineRegistry is
1312 * always set: it's either the global registry UUID or a machine UUID when
1313 * loading from a per-machine registry.
1314 *
1315 * @param aParent Parent medium disk or NULL for a root (base) medium.
1316 * @param aDeviceType Device type of the medium.
1317 * @param uuidMachineRegistry The registry to which this medium should be
1318 * added (global registry UUID or machine UUID).
1319 * @param data Configuration settings.
1320 * @param strMachineFolder The machine folder with which to resolve relative paths;
1321 * if empty, then we use the VirtualBox home directory
1322 *
1323 * @note Locks the medium tree for writing.
1324 */
1325HRESULT Medium::initOne(Medium *aParent,
1326 DeviceType_T aDeviceType,
1327 const Guid &uuidMachineRegistry,
1328 const settings::Medium &data,
1329 const Utf8Str &strMachineFolder)
1330{
1331 HRESULT rc;
1332
1333 if (uuidMachineRegistry.isValid() && !uuidMachineRegistry.isZero())
1334 m->llRegistryIDs.push_back(uuidMachineRegistry);
1335
1336 /* register with VirtualBox/parent early, since uninit() will
1337 * unconditionally unregister on failure */
1338 if (aParent)
1339 {
1340 // differencing medium: add to parent
1341 AutoWriteLock treeLock(m->pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1342 // no need to check maximum depth as settings reading did it
1343 i_setParent(aParent);
1344 }
1345
1346 /* see below why we don't call Medium::i_queryInfo (and therefore treat
1347 * the medium as inaccessible for now */
1348 m->state = MediumState_Inaccessible;
1349 m->strLastAccessError = tr("Accessibility check was not yet performed");
1350
1351 /* required */
1352 unconst(m->id) = data.uuid;
1353
1354 /* assume not a host drive */
1355 m->hostDrive = false;
1356
1357 /* optional */
1358 m->strDescription = data.strDescription;
1359
1360 /* required */
1361 if (aDeviceType == DeviceType_HardDisk)
1362 {
1363 AssertReturn(!data.strFormat.isEmpty(), E_FAIL);
1364 rc = i_setFormat(data.strFormat);
1365 if (FAILED(rc)) return rc;
1366 }
1367 else
1368 {
1369 /// @todo handle host drive settings here as well?
1370 if (!data.strFormat.isEmpty())
1371 rc = i_setFormat(data.strFormat);
1372 else
1373 rc = i_setFormat("RAW");
1374 if (FAILED(rc)) return rc;
1375 }
1376
1377 /* optional, only for diffs, default is false; we can only auto-reset
1378 * diff media so they must have a parent */
1379 if (aParent != NULL)
1380 m->autoReset = data.fAutoReset;
1381 else
1382 m->autoReset = false;
1383
1384 /* properties (after setting the format as it populates the map). Note that
1385 * if some properties are not supported but present in the settings file,
1386 * they will still be read and accessible (for possible backward
1387 * compatibility; we can also clean them up from the XML upon next
1388 * XML format version change if we wish) */
1389 for (settings::StringsMap::const_iterator it = data.properties.begin();
1390 it != data.properties.end();
1391 ++it)
1392 {
1393 const Utf8Str &name = it->first;
1394 const Utf8Str &value = it->second;
1395 m->mapProperties[name] = value;
1396 }
1397
1398 /* try to decrypt an optional iSCSI initiator secret */
1399 settings::StringsMap::const_iterator itCph = data.properties.find("InitiatorSecretEncrypted");
1400 if ( itCph != data.properties.end()
1401 && !itCph->second.isEmpty())
1402 {
1403 Utf8Str strPlaintext;
1404 int vrc = m->pVirtualBox->i_decryptSetting(&strPlaintext, itCph->second);
1405 if (RT_SUCCESS(vrc))
1406 m->mapProperties["InitiatorSecret"] = strPlaintext;
1407 }
1408
1409 Utf8Str strFull;
1410 if (m->formatObj->i_getCapabilities() & MediumFormatCapabilities_File)
1411 {
1412 // compose full path of the medium, if it's not fully qualified...
1413 // slightly convoluted logic here. If the caller has given us a
1414 // machine folder, then a relative path will be relative to that:
1415 if ( !strMachineFolder.isEmpty()
1416 && !RTPathStartsWithRoot(data.strLocation.c_str())
1417 )
1418 {
1419 strFull = strMachineFolder;
1420 strFull += RTPATH_SLASH;
1421 strFull += data.strLocation;
1422 }
1423 else
1424 {
1425 // Otherwise use the old VirtualBox "make absolute path" logic:
1426 rc = m->pVirtualBox->i_calculateFullPath(data.strLocation, strFull);
1427 if (FAILED(rc)) return rc;
1428 }
1429 }
1430 else
1431 strFull = data.strLocation;
1432
1433 rc = i_setLocation(strFull);
1434 if (FAILED(rc)) return rc;
1435
1436 if (aDeviceType == DeviceType_HardDisk)
1437 {
1438 /* type is only for base hard disks */
1439 if (m->pParent.isNull())
1440 m->type = data.hdType;
1441 }
1442 else if (aDeviceType == DeviceType_DVD)
1443 m->type = MediumType_Readonly;
1444 else
1445 m->type = MediumType_Writethrough;
1446
1447 /* remember device type for correct unregistering later */
1448 m->devType = aDeviceType;
1449
1450 LogFlowThisFunc(("m->strLocationFull='%s', m->strFormat=%s, m->id={%RTuuid}\n",
1451 m->strLocationFull.c_str(), m->strFormat.c_str(), m->id.raw()));
1452
1453 return S_OK;
1454}
1455
1456/**
1457 * Initializes the medium object and its children by loading its data from the
1458 * given settings node. The medium will always be opened read/write.
1459 *
1460 * In this case, since we're loading from a registry, uuidMachineRegistry is
1461 * always set: it's either the global registry UUID or a machine UUID when
1462 * loading from a per-machine registry.
1463 *
1464 * @param aVirtualBox VirtualBox object.
1465 * @param aParent Parent medium disk or NULL for a root (base) medium.
1466 * @param aDeviceType Device type of the medium.
1467 * @param uuidMachineRegistry The registry to which this medium should be added
1468 * (global registry UUID or machine UUID).
1469 * @param data Configuration settings.
1470 * @param strMachineFolder The machine folder with which to resolve relative
1471 * paths; if empty, then we use the VirtualBox home directory
1472 * @param mediaTreeLock Autolock.
1473 *
1474 * @note Locks the medium tree for writing.
1475 */
1476HRESULT Medium::init(VirtualBox *aVirtualBox,
1477 Medium *aParent,
1478 DeviceType_T aDeviceType,
1479 const Guid &uuidMachineRegistry,
1480 const settings::Medium &data,
1481 const Utf8Str &strMachineFolder,
1482 AutoWriteLock &mediaTreeLock)
1483{
1484 using namespace settings;
1485
1486 Assert(aVirtualBox->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
1487 AssertReturn(aVirtualBox, E_INVALIDARG);
1488
1489 /* Enclose the state transition NotReady->InInit->Ready */
1490 AutoInitSpan autoInitSpan(this);
1491 AssertReturn(autoInitSpan.isOk(), E_FAIL);
1492
1493 unconst(m->pVirtualBox) = aVirtualBox;
1494
1495 // Do not inline this method call, as the purpose of having this separate
1496 // is to save on stack size. Less local variables are the key for reaching
1497 // deep recursion levels with small stack (XPCOM/g++ without optimization).
1498 HRESULT rc = initOne(aParent, aDeviceType, uuidMachineRegistry, data, strMachineFolder);
1499
1500
1501 /* Don't call Medium::i_queryInfo for registered media to prevent the calling
1502 * thread (i.e. the VirtualBox server startup thread) from an unexpected
1503 * freeze but mark it as initially inaccessible instead. The vital UUID,
1504 * location and format properties are read from the registry file above; to
1505 * get the actual state and the rest of the data, the user will have to call
1506 * COMGETTER(State). */
1507
1508 /* load all children */
1509 for (settings::MediaList::const_iterator it = data.llChildren.begin();
1510 it != data.llChildren.end();
1511 ++it)
1512 {
1513 const settings::Medium &med = *it;
1514
1515 ComObjPtr<Medium> pMedium;
1516 pMedium.createObject();
1517 rc = pMedium->init(aVirtualBox,
1518 this, // parent
1519 aDeviceType,
1520 uuidMachineRegistry,
1521 med, // child data
1522 strMachineFolder,
1523 mediaTreeLock);
1524 if (FAILED(rc)) break;
1525
1526 rc = m->pVirtualBox->i_registerMedium(pMedium, &pMedium, mediaTreeLock);
1527 if (FAILED(rc)) break;
1528 }
1529
1530 /* Confirm a successful initialization when it's the case */
1531 if (SUCCEEDED(rc))
1532 autoInitSpan.setSucceeded();
1533
1534 return rc;
1535}
1536
1537/**
1538 * Initializes the medium object by providing the host drive information.
1539 * Not used for anything but the host floppy/host DVD case.
1540 *
1541 * There is no registry for this case.
1542 *
1543 * @param aVirtualBox VirtualBox object.
1544 * @param aDeviceType Device type of the medium.
1545 * @param aLocation Location of the host drive.
1546 * @param aDescription Comment for this host drive.
1547 *
1548 * @note Locks VirtualBox lock for writing.
1549 */
1550HRESULT Medium::init(VirtualBox *aVirtualBox,
1551 DeviceType_T aDeviceType,
1552 const Utf8Str &aLocation,
1553 const Utf8Str &aDescription /* = Utf8Str::Empty */)
1554{
1555 ComAssertRet(aDeviceType == DeviceType_DVD || aDeviceType == DeviceType_Floppy, E_INVALIDARG);
1556 ComAssertRet(!aLocation.isEmpty(), E_INVALIDARG);
1557
1558 /* Enclose the state transition NotReady->InInit->Ready */
1559 AutoInitSpan autoInitSpan(this);
1560 AssertReturn(autoInitSpan.isOk(), E_FAIL);
1561
1562 unconst(m->pVirtualBox) = aVirtualBox;
1563
1564 // We do not store host drives in VirtualBox.xml or anywhere else, so if we want
1565 // host drives to be identifiable by UUID and not give the drive a different UUID
1566 // every time VirtualBox starts, we need to fake a reproducible UUID here:
1567 RTUUID uuid;
1568 RTUuidClear(&uuid);
1569 if (aDeviceType == DeviceType_DVD)
1570 memcpy(&uuid.au8[0], "DVD", 3);
1571 else
1572 memcpy(&uuid.au8[0], "FD", 2);
1573 /* use device name, adjusted to the end of uuid, shortened if necessary */
1574 size_t lenLocation = aLocation.length();
1575 if (lenLocation > 12)
1576 memcpy(&uuid.au8[4], aLocation.c_str() + (lenLocation - 12), 12);
1577 else
1578 memcpy(&uuid.au8[4 + 12 - lenLocation], aLocation.c_str(), lenLocation);
1579 unconst(m->id) = uuid;
1580
1581 if (aDeviceType == DeviceType_DVD)
1582 m->type = MediumType_Readonly;
1583 else
1584 m->type = MediumType_Writethrough;
1585 m->devType = aDeviceType;
1586 m->state = MediumState_Created;
1587 m->hostDrive = true;
1588 HRESULT rc = i_setFormat("RAW");
1589 if (FAILED(rc)) return rc;
1590 rc = i_setLocation(aLocation);
1591 if (FAILED(rc)) return rc;
1592 m->strDescription = aDescription;
1593
1594 autoInitSpan.setSucceeded();
1595 return S_OK;
1596}
1597
1598/**
1599 * Uninitializes the instance.
1600 *
1601 * Called either from FinalRelease() or by the parent when it gets destroyed.
1602 *
1603 * @note All children of this medium get uninitialized by calling their
1604 * uninit() methods.
1605 */
1606void Medium::uninit()
1607{
1608 /* It is possible that some previous/concurrent uninit has already cleared
1609 * the pVirtualBox reference, and in this case we don't need to continue.
1610 * Normally this would be handled through the AutoUninitSpan magic, however
1611 * this cannot be done at this point as the media tree must be locked
1612 * before reaching the AutoUninitSpan, otherwise deadlocks can happen.
1613 *
1614 * NOTE: The tree lock is higher priority than the medium caller and medium
1615 * object locks, i.e. the medium caller may have to be released and be
1616 * re-acquired in the right place later. See Medium::getParent() for sample
1617 * code how to do this safely. */
1618 VirtualBox *pVirtualBox = m->pVirtualBox;
1619 if (!pVirtualBox)
1620 return;
1621
1622 /* Caller must not hold the object or media tree lock over uninit(). */
1623 Assert(!isWriteLockOnCurrentThread());
1624 Assert(!pVirtualBox->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
1625
1626 AutoWriteLock treeLock(pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1627
1628 /* Enclose the state transition Ready->InUninit->NotReady */
1629 AutoUninitSpan autoUninitSpan(this);
1630 if (autoUninitSpan.uninitDone())
1631 return;
1632
1633 if (!m->formatObj.isNull())
1634 m->formatObj.setNull();
1635
1636 if (m->state == MediumState_Deleting)
1637 {
1638 /* This medium has been already deleted (directly or as part of a
1639 * merge). Reparenting has already been done. */
1640 Assert(m->pParent.isNull());
1641 }
1642 else
1643 {
1644 MediaList llChildren(m->llChildren);
1645 m->llChildren.clear();
1646 autoUninitSpan.setSucceeded();
1647
1648 while (!llChildren.empty())
1649 {
1650 ComObjPtr<Medium> pChild = llChildren.front();
1651 llChildren.pop_front();
1652 pChild->m->pParent.setNull();
1653 treeLock.release();
1654 pChild->uninit();
1655 treeLock.acquire();
1656 }
1657
1658 if (m->pParent)
1659 {
1660 // this is a differencing disk: then remove it from the parent's children list
1661 i_deparent();
1662 }
1663 }
1664
1665 unconst(m->pVirtualBox) = NULL;
1666}
1667
1668/**
1669 * Internal helper that removes "this" from the list of children of its
1670 * parent. Used in uninit() and other places when reparenting is necessary.
1671 *
1672 * The caller must hold the medium tree lock!
1673 */
1674void Medium::i_deparent()
1675{
1676 MediaList &llParent = m->pParent->m->llChildren;
1677 for (MediaList::iterator it = llParent.begin();
1678 it != llParent.end();
1679 ++it)
1680 {
1681 Medium *pParentsChild = *it;
1682 if (this == pParentsChild)
1683 {
1684 llParent.erase(it);
1685 break;
1686 }
1687 }
1688 m->pParent.setNull();
1689}
1690
1691/**
1692 * Internal helper that removes "this" from the list of children of its
1693 * parent. Used in uninit() and other places when reparenting is necessary.
1694 *
1695 * The caller must hold the medium tree lock!
1696 */
1697void Medium::i_setParent(const ComObjPtr<Medium> &pParent)
1698{
1699 m->pParent = pParent;
1700 if (pParent)
1701 pParent->m->llChildren.push_back(this);
1702}
1703
1704
1705////////////////////////////////////////////////////////////////////////////////
1706//
1707// IMedium public methods
1708//
1709////////////////////////////////////////////////////////////////////////////////
1710
1711HRESULT Medium::getId(com::Guid &aId)
1712{
1713 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1714
1715 aId = m->id;
1716
1717 return S_OK;
1718}
1719
1720HRESULT Medium::getDescription(com::Utf8Str &aDescription)
1721{
1722 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1723
1724 aDescription = m->strDescription;
1725
1726 return S_OK;
1727}
1728
1729HRESULT Medium::setDescription(const com::Utf8Str &aDescription)
1730{
1731 /// @todo update m->strDescription and save the global registry (and local
1732 /// registries of portable VMs referring to this medium), this will also
1733 /// require to add the mRegistered flag to data
1734
1735 HRESULT rc = S_OK;
1736
1737 MediumLockList *pMediumLockList(new MediumLockList());
1738
1739 try
1740 {
1741 // locking: we need the tree lock first because we access parent pointers
1742 // and we need to write-lock the media involved
1743 uint32_t cHandles = 2;
1744 LockHandle* pHandles[2] = { &m->pVirtualBox->i_getMediaTreeLockHandle(),
1745 this->lockHandle() };
1746
1747 AutoWriteLock alock(cHandles,
1748 pHandles
1749 COMMA_LOCKVAL_SRC_POS);
1750
1751 /* Build the lock list. */
1752 alock.release();
1753 rc = i_createMediumLockList(true /* fFailIfInaccessible */,
1754 this /* pToLockWrite */,
1755 true /* fMediumLockWriteAll */,
1756 NULL,
1757 *pMediumLockList);
1758 alock.acquire();
1759
1760 if (FAILED(rc))
1761 {
1762 throw setError(rc,
1763 tr("Failed to create medium lock list for '%s'"),
1764 i_getLocationFull().c_str());
1765 }
1766
1767 alock.release();
1768 rc = pMediumLockList->Lock();
1769 alock.acquire();
1770
1771 if (FAILED(rc))
1772 {
1773 throw setError(rc,
1774 tr("Failed to lock media '%s'"),
1775 i_getLocationFull().c_str());
1776 }
1777
1778 /* Set a new description */
1779 if (SUCCEEDED(rc))
1780 {
1781 m->strDescription = aDescription;
1782 }
1783
1784 // save the settings
1785 i_markRegistriesModified();
1786 m->pVirtualBox->i_saveModifiedRegistries();
1787 }
1788 catch (HRESULT aRC) { rc = aRC; }
1789
1790 delete pMediumLockList;
1791
1792 return rc;
1793}
1794
1795HRESULT Medium::getState(MediumState_T *aState)
1796{
1797 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1798 *aState = m->state;
1799
1800 return S_OK;
1801}
1802
1803HRESULT Medium::getVariant(std::vector<MediumVariant_T> &aVariant)
1804{
1805 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1806
1807 const size_t cBits = sizeof(MediumVariant_T) * 8;
1808 aVariant.resize(cBits);
1809 for (size_t i = 0; i < cBits; ++i)
1810 aVariant[i] = (MediumVariant_T)(m->variant & RT_BIT(i));
1811
1812 return S_OK;
1813}
1814
1815HRESULT Medium::getLocation(com::Utf8Str &aLocation)
1816{
1817 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1818
1819 aLocation = m->strLocationFull;
1820
1821 return S_OK;
1822}
1823
1824HRESULT Medium::getName(com::Utf8Str &aName)
1825{
1826 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1827
1828 aName = i_getName();
1829
1830 return S_OK;
1831}
1832
1833HRESULT Medium::getDeviceType(DeviceType_T *aDeviceType)
1834{
1835 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1836
1837 *aDeviceType = m->devType;
1838
1839 return S_OK;
1840}
1841
1842HRESULT Medium::getHostDrive(BOOL *aHostDrive)
1843{
1844 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1845
1846 *aHostDrive = m->hostDrive;
1847
1848 return S_OK;
1849}
1850
1851HRESULT Medium::getSize(LONG64 *aSize)
1852{
1853 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1854
1855 *aSize = m->size;
1856
1857 return S_OK;
1858}
1859
1860HRESULT Medium::getFormat(com::Utf8Str &aFormat)
1861{
1862 /* no need to lock, m->strFormat is const */
1863
1864 aFormat = m->strFormat;
1865 return S_OK;
1866}
1867
1868HRESULT Medium::getMediumFormat(ComPtr<IMediumFormat> &aMediumFormat)
1869{
1870 /* no need to lock, m->formatObj is const */
1871 m->formatObj.queryInterfaceTo(aMediumFormat.asOutParam());
1872
1873 return S_OK;
1874}
1875
1876HRESULT Medium::getType(AutoCaller &autoCaller, MediumType_T *aType)
1877{
1878 NOREF(autoCaller);
1879 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1880
1881 *aType = m->type;
1882
1883 return S_OK;
1884}
1885
1886HRESULT Medium::setType(AutoCaller &autoCaller, MediumType_T aType)
1887{
1888 autoCaller.release();
1889
1890 /* It is possible that some previous/concurrent uninit has already cleared
1891 * the pVirtualBox reference, see #uninit(). */
1892 ComObjPtr<VirtualBox> pVirtualBox(m->pVirtualBox);
1893
1894 // we access m->pParent
1895 AutoReadLock treeLock(!pVirtualBox.isNull() ? &pVirtualBox->i_getMediaTreeLockHandle() : NULL COMMA_LOCKVAL_SRC_POS);
1896
1897 autoCaller.add();
1898 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1899
1900 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
1901
1902 switch (m->state)
1903 {
1904 case MediumState_Created:
1905 case MediumState_Inaccessible:
1906 break;
1907 default:
1908 return i_setStateError();
1909 }
1910
1911 if (m->type == aType)
1912 {
1913 /* Nothing to do */
1914 return S_OK;
1915 }
1916
1917 DeviceType_T devType = i_getDeviceType();
1918 // DVD media can only be readonly.
1919 if (devType == DeviceType_DVD && aType != MediumType_Readonly)
1920 return setError(VBOX_E_INVALID_OBJECT_STATE,
1921 tr("Cannot change the type of DVD medium '%s'"),
1922 m->strLocationFull.c_str());
1923 // Floppy media can only be writethrough or readonly.
1924 if ( devType == DeviceType_Floppy
1925 && aType != MediumType_Writethrough
1926 && aType != MediumType_Readonly)
1927 return setError(VBOX_E_INVALID_OBJECT_STATE,
1928 tr("Cannot change the type of floppy medium '%s'"),
1929 m->strLocationFull.c_str());
1930
1931 /* cannot change the type of a differencing medium */
1932 if (m->pParent)
1933 return setError(VBOX_E_INVALID_OBJECT_STATE,
1934 tr("Cannot change the type of medium '%s' because it is a differencing medium"),
1935 m->strLocationFull.c_str());
1936
1937 /* Cannot change the type of a medium being in use by more than one VM.
1938 * If the change is to Immutable or MultiAttach then it must not be
1939 * directly attached to any VM, otherwise the assumptions about indirect
1940 * attachment elsewhere are violated and the VM becomes inaccessible.
1941 * Attaching an immutable medium triggers the diff creation, and this is
1942 * vital for the correct operation. */
1943 if ( m->backRefs.size() > 1
1944 || ( ( aType == MediumType_Immutable
1945 || aType == MediumType_MultiAttach)
1946 && m->backRefs.size() > 0))
1947 return setError(VBOX_E_INVALID_OBJECT_STATE,
1948 tr("Cannot change the type of medium '%s' because it is attached to %d virtual machines"),
1949 m->strLocationFull.c_str(), m->backRefs.size());
1950
1951 switch (aType)
1952 {
1953 case MediumType_Normal:
1954 case MediumType_Immutable:
1955 case MediumType_MultiAttach:
1956 {
1957 /* normal can be easily converted to immutable and vice versa even
1958 * if they have children as long as they are not attached to any
1959 * machine themselves */
1960 break;
1961 }
1962 case MediumType_Writethrough:
1963 case MediumType_Shareable:
1964 case MediumType_Readonly:
1965 {
1966 /* cannot change to writethrough, shareable or readonly
1967 * if there are children */
1968 if (i_getChildren().size() != 0)
1969 return setError(VBOX_E_OBJECT_IN_USE,
1970 tr("Cannot change type for medium '%s' since it has %d child media"),
1971 m->strLocationFull.c_str(), i_getChildren().size());
1972 if (aType == MediumType_Shareable)
1973 {
1974 MediumVariant_T variant = i_getVariant();
1975 if (!(variant & MediumVariant_Fixed))
1976 return setError(VBOX_E_INVALID_OBJECT_STATE,
1977 tr("Cannot change type for medium '%s' to 'Shareable' since it is a dynamic medium storage unit"),
1978 m->strLocationFull.c_str());
1979 }
1980 else if (aType == MediumType_Readonly && devType == DeviceType_HardDisk)
1981 {
1982 // Readonly hard disks are not allowed, this medium type is reserved for
1983 // DVDs and floppy images at the moment. Later we might allow readonly hard
1984 // disks, but that's extremely unusual and many guest OSes will have trouble.
1985 return setError(VBOX_E_INVALID_OBJECT_STATE,
1986 tr("Cannot change type for medium '%s' to 'Readonly' since it is a hard disk"),
1987 m->strLocationFull.c_str());
1988 }
1989 break;
1990 }
1991 default:
1992 AssertFailedReturn(E_FAIL);
1993 }
1994
1995 if (aType == MediumType_MultiAttach)
1996 {
1997 // This type is new with VirtualBox 4.0 and therefore requires settings
1998 // version 1.11 in the settings backend. Unfortunately it is not enough to do
1999 // the usual routine in MachineConfigFile::bumpSettingsVersionIfNeeded() for
2000 // two reasons: The medium type is a property of the media registry tree, which
2001 // can reside in the global config file (for pre-4.0 media); we would therefore
2002 // possibly need to bump the global config version. We don't want to do that though
2003 // because that might make downgrading to pre-4.0 impossible.
2004 // As a result, we can only use these two new types if the medium is NOT in the
2005 // global registry:
2006 const Guid &uuidGlobalRegistry = m->pVirtualBox->i_getGlobalRegistryId();
2007 if (i_isInRegistry(uuidGlobalRegistry))
2008 return setError(VBOX_E_INVALID_OBJECT_STATE,
2009 tr("Cannot change type for medium '%s': the media type 'MultiAttach' can only be used "
2010 "on media registered with a machine that was created with VirtualBox 4.0 or later"),
2011 m->strLocationFull.c_str());
2012 }
2013
2014 m->type = aType;
2015
2016 // save the settings
2017 mlock.release();
2018 treeLock.release();
2019 i_markRegistriesModified();
2020 m->pVirtualBox->i_saveModifiedRegistries();
2021
2022 return S_OK;
2023}
2024
2025HRESULT Medium::getAllowedTypes(std::vector<MediumType_T> &aAllowedTypes)
2026{
2027 NOREF(aAllowedTypes);
2028 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2029
2030 ReturnComNotImplemented();
2031}
2032
2033HRESULT Medium::getParent(AutoCaller &autoCaller, ComPtr<IMedium> &aParent)
2034{
2035 autoCaller.release();
2036
2037 /* It is possible that some previous/concurrent uninit has already cleared
2038 * the pVirtualBox reference, see #uninit(). */
2039 ComObjPtr<VirtualBox> pVirtualBox(m->pVirtualBox);
2040
2041 /* we access m->pParent */
2042 AutoReadLock treeLock(!pVirtualBox.isNull() ? &pVirtualBox->i_getMediaTreeLockHandle() : NULL COMMA_LOCKVAL_SRC_POS);
2043
2044 autoCaller.add();
2045 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2046
2047 m->pParent.queryInterfaceTo(aParent.asOutParam());
2048
2049 return S_OK;
2050}
2051
2052HRESULT Medium::getChildren(AutoCaller &autoCaller, std::vector<ComPtr<IMedium> > &aChildren)
2053{
2054 autoCaller.release();
2055
2056 /* It is possible that some previous/concurrent uninit has already cleared
2057 * the pVirtualBox reference, see #uninit(). */
2058 ComObjPtr<VirtualBox> pVirtualBox(m->pVirtualBox);
2059
2060 /* we access children */
2061 AutoReadLock treeLock(!pVirtualBox.isNull() ? &pVirtualBox->i_getMediaTreeLockHandle() : NULL COMMA_LOCKVAL_SRC_POS);
2062
2063 autoCaller.add();
2064 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2065
2066 MediaList children(this->i_getChildren());
2067 aChildren.resize(children.size());
2068 size_t i = 0;
2069 for (MediaList::const_iterator it = children.begin(); it != children.end(); ++it, ++i)
2070 (*it).queryInterfaceTo(aChildren[i].asOutParam());
2071 return S_OK;
2072}
2073
2074HRESULT Medium::getBase(AutoCaller &autoCaller, ComPtr<IMedium> &aBase)
2075{
2076 autoCaller.release();
2077
2078 /* i_getBase() will do callers/locking */
2079 i_getBase().queryInterfaceTo(aBase.asOutParam());
2080
2081 return S_OK;
2082}
2083
2084HRESULT Medium::getReadOnly(AutoCaller &autoCaller, BOOL *aReadOnly)
2085{
2086 autoCaller.release();
2087
2088 /* isReadOnly() will do locking */
2089 *aReadOnly = i_isReadOnly();
2090
2091 return S_OK;
2092}
2093
2094HRESULT Medium::getLogicalSize(LONG64 *aLogicalSize)
2095{
2096 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2097
2098 *aLogicalSize = m->logicalSize;
2099
2100 return S_OK;
2101}
2102
2103HRESULT Medium::getAutoReset(BOOL *aAutoReset)
2104{
2105 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2106
2107 if (m->pParent.isNull())
2108 *aAutoReset = FALSE;
2109 else
2110 *aAutoReset = m->autoReset;
2111
2112 return S_OK;
2113}
2114
2115HRESULT Medium::setAutoReset(BOOL aAutoReset)
2116{
2117 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
2118
2119 if (m->pParent.isNull())
2120 return setError(VBOX_E_NOT_SUPPORTED,
2121 tr("Medium '%s' is not differencing"),
2122 m->strLocationFull.c_str());
2123
2124 if (m->autoReset != !!aAutoReset)
2125 {
2126 m->autoReset = !!aAutoReset;
2127
2128 // save the settings
2129 mlock.release();
2130 i_markRegistriesModified();
2131 m->pVirtualBox->i_saveModifiedRegistries();
2132 }
2133
2134 return S_OK;
2135}
2136
2137HRESULT Medium::getLastAccessError(com::Utf8Str &aLastAccessError)
2138{
2139 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2140
2141 aLastAccessError = m->strLastAccessError;
2142
2143 return S_OK;
2144}
2145
2146HRESULT Medium::getMachineIds(std::vector<com::Guid> &aMachineIds)
2147{
2148 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2149
2150 if (m->backRefs.size() != 0)
2151 {
2152 BackRefList brlist(m->backRefs);
2153 aMachineIds.resize(brlist.size());
2154 size_t i = 0;
2155 for (BackRefList::const_iterator it = brlist.begin(); it != brlist.end(); ++it, ++i)
2156 aMachineIds[i] = it->machineId;
2157 }
2158
2159 return S_OK;
2160}
2161
2162HRESULT Medium::setIds(AutoCaller &autoCaller,
2163 BOOL aSetImageId,
2164 const com::Guid &aImageId,
2165 BOOL aSetParentId,
2166 const com::Guid &aParentId)
2167{
2168 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2169
2170 switch (m->state)
2171 {
2172 case MediumState_Created:
2173 break;
2174 default:
2175 return i_setStateError();
2176 }
2177
2178 Guid imageId, parentId;
2179 if (aSetImageId)
2180 {
2181 if (aImageId.isZero())
2182 imageId.create();
2183 else
2184 {
2185 imageId = aImageId;
2186 if (!imageId.isValid())
2187 return setError(E_INVALIDARG, tr("Argument %s is invalid"), "aImageId");
2188 }
2189 }
2190 if (aSetParentId)
2191 {
2192 if (aParentId.isZero())
2193 parentId.create();
2194 else
2195 parentId = aParentId;
2196 }
2197
2198 unconst(m->uuidImage) = imageId;
2199 unconst(m->uuidParentImage) = parentId;
2200
2201 // must not hold any locks before calling Medium::i_queryInfo
2202 alock.release();
2203
2204 HRESULT rc = i_queryInfo(!!aSetImageId /* fSetImageId */,
2205 !!aSetParentId /* fSetParentId */,
2206 autoCaller);
2207
2208 return rc;
2209}
2210
2211HRESULT Medium::refreshState(AutoCaller &autoCaller, MediumState_T *aState)
2212{
2213 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2214
2215 HRESULT rc = S_OK;
2216
2217 switch (m->state)
2218 {
2219 case MediumState_Created:
2220 case MediumState_Inaccessible:
2221 case MediumState_LockedRead:
2222 {
2223 // must not hold any locks before calling Medium::i_queryInfo
2224 alock.release();
2225
2226 rc = i_queryInfo(false /* fSetImageId */, false /* fSetParentId */,
2227 autoCaller);
2228
2229 alock.acquire();
2230 break;
2231 }
2232 default:
2233 break;
2234 }
2235
2236 *aState = m->state;
2237
2238 return rc;
2239}
2240
2241HRESULT Medium::getSnapshotIds(const com::Guid &aMachineId,
2242 std::vector<com::Guid> &aSnapshotIds)
2243{
2244 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2245
2246 for (BackRefList::const_iterator it = m->backRefs.begin();
2247 it != m->backRefs.end(); ++it)
2248 {
2249 if (it->machineId == aMachineId)
2250 {
2251 size_t size = it->llSnapshotIds.size();
2252
2253 /* if the medium is attached to the machine in the current state, we
2254 * return its ID as the first element of the array */
2255 if (it->fInCurState)
2256 ++size;
2257
2258 if (size > 0)
2259 {
2260 aSnapshotIds.resize(size);
2261
2262 size_t j = 0;
2263 if (it->fInCurState)
2264 aSnapshotIds[j++] = it->machineId.toUtf16();
2265
2266 for(GuidList::const_iterator jt = it->llSnapshotIds.begin(); jt != it->llSnapshotIds.end(); ++jt, ++j)
2267 aSnapshotIds[j] = (*jt);
2268 }
2269
2270 break;
2271 }
2272 }
2273
2274 return S_OK;
2275}
2276
2277HRESULT Medium::lockRead(ComPtr<IToken> &aToken)
2278{
2279 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2280
2281 /* Wait for a concurrently running Medium::i_queryInfo to complete. */
2282 if (m->queryInfoRunning)
2283 {
2284 /* Must not hold the media tree lock, as Medium::i_queryInfo needs this
2285 * lock and thus we would run into a deadlock here. */
2286 Assert(!m->pVirtualBox->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
2287 while (m->queryInfoRunning)
2288 {
2289 alock.release();
2290 /* must not hold the object lock now */
2291 Assert(!isWriteLockOnCurrentThread());
2292 {
2293 AutoReadLock qlock(m->queryInfoSem COMMA_LOCKVAL_SRC_POS);
2294 }
2295 alock.acquire();
2296 }
2297 }
2298
2299 HRESULT rc = S_OK;
2300
2301 switch (m->state)
2302 {
2303 case MediumState_Created:
2304 case MediumState_Inaccessible:
2305 case MediumState_LockedRead:
2306 {
2307 ++m->readers;
2308
2309 ComAssertMsgBreak(m->readers != 0, ("Counter overflow"), rc = E_FAIL);
2310
2311 /* Remember pre-lock state */
2312 if (m->state != MediumState_LockedRead)
2313 m->preLockState = m->state;
2314
2315 LogFlowThisFunc(("Okay - prev state=%d readers=%d\n", m->state, m->readers));
2316 m->state = MediumState_LockedRead;
2317
2318 ComObjPtr<MediumLockToken> pToken;
2319 rc = pToken.createObject();
2320 if (SUCCEEDED(rc))
2321 rc = pToken->init(this, false /* fWrite */);
2322 if (FAILED(rc))
2323 {
2324 --m->readers;
2325 if (m->readers == 0)
2326 m->state = m->preLockState;
2327 return rc;
2328 }
2329
2330 pToken.queryInterfaceTo(aToken.asOutParam());
2331 break;
2332 }
2333 default:
2334 {
2335 LogFlowThisFunc(("Failing - state=%d\n", m->state));
2336 rc = i_setStateError();
2337 break;
2338 }
2339 }
2340
2341 return rc;
2342}
2343
2344/**
2345 * @note @a aState may be NULL if the state value is not needed (only for
2346 * in-process calls).
2347 */
2348HRESULT Medium::i_unlockRead(MediumState_T *aState)
2349{
2350 AutoCaller autoCaller(this);
2351 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2352
2353 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2354
2355 HRESULT rc = S_OK;
2356
2357 switch (m->state)
2358 {
2359 case MediumState_LockedRead:
2360 {
2361 ComAssertMsgBreak(m->readers != 0, ("Counter underflow"), rc = E_FAIL);
2362 --m->readers;
2363
2364 /* Reset the state after the last reader */
2365 if (m->readers == 0)
2366 {
2367 m->state = m->preLockState;
2368 /* There are cases where we inject the deleting state into
2369 * a medium locked for reading. Make sure #unmarkForDeletion()
2370 * gets the right state afterwards. */
2371 if (m->preLockState == MediumState_Deleting)
2372 m->preLockState = MediumState_Created;
2373 }
2374
2375 LogFlowThisFunc(("new state=%d\n", m->state));
2376 break;
2377 }
2378 default:
2379 {
2380 LogFlowThisFunc(("Failing - state=%d\n", m->state));
2381 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
2382 tr("Medium '%s' is not locked for reading"),
2383 m->strLocationFull.c_str());
2384 break;
2385 }
2386 }
2387
2388 /* return the current state after */
2389 if (aState)
2390 *aState = m->state;
2391
2392 return rc;
2393}
2394HRESULT Medium::lockWrite(ComPtr<IToken> &aToken)
2395{
2396 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2397
2398 /* Wait for a concurrently running Medium::i_queryInfo to complete. */
2399 if (m->queryInfoRunning)
2400 {
2401 /* Must not hold the media tree lock, as Medium::i_queryInfo needs this
2402 * lock and thus we would run into a deadlock here. */
2403 Assert(!m->pVirtualBox->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
2404 while (m->queryInfoRunning)
2405 {
2406 alock.release();
2407 /* must not hold the object lock now */
2408 Assert(!isWriteLockOnCurrentThread());
2409 {
2410 AutoReadLock qlock(m->queryInfoSem COMMA_LOCKVAL_SRC_POS);
2411 }
2412 alock.acquire();
2413 }
2414 }
2415
2416 HRESULT rc = S_OK;
2417
2418 switch (m->state)
2419 {
2420 case MediumState_Created:
2421 case MediumState_Inaccessible:
2422 {
2423 m->preLockState = m->state;
2424
2425 LogFlowThisFunc(("Okay - prev state=%d locationFull=%s\n", m->state, i_getLocationFull().c_str()));
2426 m->state = MediumState_LockedWrite;
2427
2428 ComObjPtr<MediumLockToken> pToken;
2429 rc = pToken.createObject();
2430 if (SUCCEEDED(rc))
2431 rc = pToken->init(this, true /* fWrite */);
2432 if (FAILED(rc))
2433 {
2434 m->state = m->preLockState;
2435 return rc;
2436 }
2437
2438 pToken.queryInterfaceTo(aToken.asOutParam());
2439 break;
2440 }
2441 default:
2442 {
2443 LogFlowThisFunc(("Failing - state=%d locationFull=%s\n", m->state, i_getLocationFull().c_str()));
2444 rc = i_setStateError();
2445 break;
2446 }
2447 }
2448
2449 return rc;
2450}
2451
2452/**
2453 * @note @a aState may be NULL if the state value is not needed (only for
2454 * in-process calls).
2455 */
2456HRESULT Medium::i_unlockWrite(MediumState_T *aState)
2457{
2458 AutoCaller autoCaller(this);
2459 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2460
2461 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2462
2463 HRESULT rc = S_OK;
2464
2465 switch (m->state)
2466 {
2467 case MediumState_LockedWrite:
2468 {
2469 m->state = m->preLockState;
2470 /* There are cases where we inject the deleting state into
2471 * a medium locked for writing. Make sure #unmarkForDeletion()
2472 * gets the right state afterwards. */
2473 if (m->preLockState == MediumState_Deleting)
2474 m->preLockState = MediumState_Created;
2475 LogFlowThisFunc(("new state=%d locationFull=%s\n", m->state, i_getLocationFull().c_str()));
2476 break;
2477 }
2478 default:
2479 {
2480 LogFlowThisFunc(("Failing - state=%d locationFull=%s\n", m->state, i_getLocationFull().c_str()));
2481 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
2482 tr("Medium '%s' is not locked for writing"),
2483 m->strLocationFull.c_str());
2484 break;
2485 }
2486 }
2487
2488 /* return the current state after */
2489 if (aState)
2490 *aState = m->state;
2491
2492 return rc;
2493}
2494
2495HRESULT Medium::close(AutoCaller &aAutoCaller)
2496{
2497 // make a copy of VirtualBox pointer which gets nulled by uninit()
2498 ComObjPtr<VirtualBox> pVirtualBox(m->pVirtualBox);
2499
2500 MultiResult mrc = i_close(aAutoCaller);
2501
2502 pVirtualBox->i_saveModifiedRegistries();
2503
2504 return mrc;
2505}
2506
2507HRESULT Medium::getProperty(const com::Utf8Str &aName,
2508 com::Utf8Str &aValue)
2509{
2510 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2511
2512 settings::StringsMap::const_iterator it = m->mapProperties.find(aName);
2513 if (it == m->mapProperties.end())
2514 {
2515 if (!aName.startsWith("Special/"))
2516 return setError(VBOX_E_OBJECT_NOT_FOUND,
2517 tr("Property '%s' does not exist"), aName.c_str());
2518 else
2519 /* be more silent here */
2520 return VBOX_E_OBJECT_NOT_FOUND;
2521 }
2522
2523 aValue = it->second;
2524
2525 return S_OK;
2526}
2527
2528HRESULT Medium::setProperty(const com::Utf8Str &aName,
2529 const com::Utf8Str &aValue)
2530{
2531 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
2532
2533 switch (m->state)
2534 {
2535 case MediumState_Created:
2536 case MediumState_Inaccessible:
2537 break;
2538 default:
2539 return i_setStateError();
2540 }
2541
2542 settings::StringsMap::iterator it = m->mapProperties.find(aName);
2543 if ( !aName.startsWith("Special/")
2544 && !i_isPropertyForFilter(aName))
2545 {
2546 if (it == m->mapProperties.end())
2547 return setError(VBOX_E_OBJECT_NOT_FOUND,
2548 tr("Property '%s' does not exist"),
2549 aName.c_str());
2550 it->second = aValue;
2551 }
2552 else
2553 {
2554 if (it == m->mapProperties.end())
2555 {
2556 if (!aValue.isEmpty())
2557 m->mapProperties[aName] = aValue;
2558 }
2559 else
2560 {
2561 if (!aValue.isEmpty())
2562 it->second = aValue;
2563 else
2564 m->mapProperties.erase(it);
2565 }
2566 }
2567
2568 // save the settings
2569 mlock.release();
2570 i_markRegistriesModified();
2571 m->pVirtualBox->i_saveModifiedRegistries();
2572
2573 return S_OK;
2574}
2575
2576HRESULT Medium::getProperties(const com::Utf8Str &aNames,
2577 std::vector<com::Utf8Str> &aReturnNames,
2578 std::vector<com::Utf8Str> &aReturnValues)
2579{
2580 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2581
2582 /// @todo make use of aNames according to the documentation
2583 NOREF(aNames);
2584
2585 aReturnNames.resize(m->mapProperties.size());
2586 aReturnValues.resize(m->mapProperties.size());
2587 size_t i = 0;
2588 for (settings::StringsMap::const_iterator it = m->mapProperties.begin();
2589 it != m->mapProperties.end();
2590 ++it, ++i)
2591 {
2592 aReturnNames[i] = it->first;
2593 aReturnValues[i] = it->second;
2594 }
2595 return S_OK;
2596}
2597
2598HRESULT Medium::setProperties(const std::vector<com::Utf8Str> &aNames,
2599 const std::vector<com::Utf8Str> &aValues)
2600{
2601 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
2602
2603 /* first pass: validate names */
2604 for (size_t i = 0;
2605 i < aNames.size();
2606 ++i)
2607 {
2608 Utf8Str strName(aNames[i]);
2609 if ( !strName.startsWith("Special/")
2610 && !i_isPropertyForFilter(strName)
2611 && m->mapProperties.find(strName) == m->mapProperties.end())
2612 return setError(VBOX_E_OBJECT_NOT_FOUND,
2613 tr("Property '%s' does not exist"), strName.c_str());
2614 }
2615
2616 /* second pass: assign */
2617 for (size_t i = 0;
2618 i < aNames.size();
2619 ++i)
2620 {
2621 Utf8Str strName(aNames[i]);
2622 Utf8Str strValue(aValues[i]);
2623 settings::StringsMap::iterator it = m->mapProperties.find(strName);
2624 if ( !strName.startsWith("Special/")
2625 && !i_isPropertyForFilter(strName))
2626 {
2627 AssertReturn(it != m->mapProperties.end(), E_FAIL);
2628 it->second = strValue;
2629 }
2630 else
2631 {
2632 if (it == m->mapProperties.end())
2633 {
2634 if (!strValue.isEmpty())
2635 m->mapProperties[strName] = strValue;
2636 }
2637 else
2638 {
2639 if (!strValue.isEmpty())
2640 it->second = strValue;
2641 else
2642 m->mapProperties.erase(it);
2643 }
2644 }
2645 }
2646
2647 // save the settings
2648 mlock.release();
2649 i_markRegistriesModified();
2650 m->pVirtualBox->i_saveModifiedRegistries();
2651
2652 return S_OK;
2653}
2654HRESULT Medium::createBaseStorage(LONG64 aLogicalSize,
2655 const std::vector<MediumVariant_T> &aVariant,
2656 ComPtr<IProgress> &aProgress)
2657{
2658 if (aLogicalSize < 0)
2659 return setError(E_INVALIDARG, tr("The medium size argument (%lld) is negative"), aLogicalSize);
2660
2661 HRESULT rc = S_OK;
2662 ComObjPtr<Progress> pProgress;
2663 Medium::Task *pTask = NULL;
2664
2665 try
2666 {
2667 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2668
2669 ULONG mediumVariantFlags = 0;
2670
2671 if (aVariant.size())
2672 {
2673 for (size_t i = 0; i < aVariant.size(); i++)
2674 mediumVariantFlags |= (ULONG)aVariant[i];
2675 }
2676
2677 mediumVariantFlags &= ((unsigned)~MediumVariant_Diff);
2678
2679 if ( !(mediumVariantFlags & MediumVariant_Fixed)
2680 && !(m->formatObj->i_getCapabilities() & MediumFormatCapabilities_CreateDynamic))
2681 throw setError(VBOX_E_NOT_SUPPORTED,
2682 tr("Medium format '%s' does not support dynamic storage creation"),
2683 m->strFormat.c_str());
2684
2685 if ( (mediumVariantFlags & MediumVariant_Fixed)
2686 && !(m->formatObj->i_getCapabilities() & MediumFormatCapabilities_CreateFixed))
2687 throw setError(VBOX_E_NOT_SUPPORTED,
2688 tr("Medium format '%s' does not support fixed storage creation"),
2689 m->strFormat.c_str());
2690
2691 if (m->state != MediumState_NotCreated)
2692 throw i_setStateError();
2693
2694 pProgress.createObject();
2695 rc = pProgress->init(m->pVirtualBox,
2696 static_cast<IMedium*>(this),
2697 (mediumVariantFlags & MediumVariant_Fixed)
2698 ? BstrFmt(tr("Creating fixed medium storage unit '%s'"), m->strLocationFull.c_str()).raw()
2699 : BstrFmt(tr("Creating dynamic medium storage unit '%s'"), m->strLocationFull.c_str()).raw(),
2700 TRUE /* aCancelable */);
2701 if (FAILED(rc))
2702 throw rc;
2703
2704 /* setup task object to carry out the operation asynchronously */
2705 pTask = new Medium::CreateBaseTask(this, pProgress, aLogicalSize,
2706 (MediumVariant_T)mediumVariantFlags);
2707 //(MediumVariant_T)aVariant);
2708 rc = pTask->rc();
2709 AssertComRC(rc);
2710 if (FAILED(rc))
2711 throw rc;
2712
2713 m->state = MediumState_Creating;
2714 }
2715 catch (HRESULT aRC) { rc = aRC; }
2716
2717 if (SUCCEEDED(rc))
2718 {
2719 rc = pTask->createThread();
2720
2721 if (SUCCEEDED(rc))
2722 pProgress.queryInterfaceTo(aProgress.asOutParam());
2723 }
2724 else if (pTask != NULL)
2725 delete pTask;
2726
2727 return rc;
2728}
2729
2730HRESULT Medium::deleteStorage(ComPtr<IProgress> &aProgress)
2731{
2732 ComObjPtr<Progress> pProgress;
2733
2734 MultiResult mrc = i_deleteStorage(&pProgress,
2735 false /* aWait */);
2736 /* Must save the registries in any case, since an entry was removed. */
2737 m->pVirtualBox->i_saveModifiedRegistries();
2738
2739 if (SUCCEEDED(mrc))
2740 pProgress.queryInterfaceTo(aProgress.asOutParam());
2741
2742 return mrc;
2743}
2744
2745HRESULT Medium::createDiffStorage(AutoCaller &autoCaller,
2746 const ComPtr<IMedium> &aTarget,
2747 const std::vector<MediumVariant_T> &aVariant,
2748 ComPtr<IProgress> &aProgress)
2749{
2750 /** @todo r=klaus The code below needs to be double checked with regard
2751 * to lock order violations, it probably causes lock order issues related
2752 * to the AutoCaller usage. */
2753 IMedium *aT = aTarget;
2754 ComObjPtr<Medium> diff = static_cast<Medium*>(aT);
2755
2756 autoCaller.release();
2757
2758 /* It is possible that some previous/concurrent uninit has already cleared
2759 * the pVirtualBox reference, see #uninit(). */
2760 ComObjPtr<VirtualBox> pVirtualBox(m->pVirtualBox);
2761
2762 // we access m->pParent
2763 AutoReadLock treeLock(!pVirtualBox.isNull() ? &pVirtualBox->i_getMediaTreeLockHandle() : NULL COMMA_LOCKVAL_SRC_POS);
2764
2765 autoCaller.add();
2766 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2767
2768 AutoMultiWriteLock2 alock(this->lockHandle(), diff->lockHandle() COMMA_LOCKVAL_SRC_POS);
2769
2770 if (m->type == MediumType_Writethrough)
2771 return setError(VBOX_E_INVALID_OBJECT_STATE,
2772 tr("Medium type of '%s' is Writethrough"),
2773 m->strLocationFull.c_str());
2774 else if (m->type == MediumType_Shareable)
2775 return setError(VBOX_E_INVALID_OBJECT_STATE,
2776 tr("Medium type of '%s' is Shareable"),
2777 m->strLocationFull.c_str());
2778 else if (m->type == MediumType_Readonly)
2779 return setError(VBOX_E_INVALID_OBJECT_STATE,
2780 tr("Medium type of '%s' is Readonly"),
2781 m->strLocationFull.c_str());
2782
2783 /* Apply the normal locking logic to the entire chain. */
2784 MediumLockList *pMediumLockList(new MediumLockList());
2785 alock.release();
2786 treeLock.release();
2787 HRESULT rc = diff->i_createMediumLockList(true /* fFailIfInaccessible */,
2788 diff /* pToLockWrite */,
2789 false /* fMediumLockWriteAll */,
2790 this,
2791 *pMediumLockList);
2792 treeLock.acquire();
2793 alock.acquire();
2794 if (FAILED(rc))
2795 {
2796 delete pMediumLockList;
2797 return rc;
2798 }
2799
2800 alock.release();
2801 treeLock.release();
2802 rc = pMediumLockList->Lock();
2803 treeLock.acquire();
2804 alock.acquire();
2805 if (FAILED(rc))
2806 {
2807 delete pMediumLockList;
2808
2809 return setError(rc, tr("Could not lock medium when creating diff '%s'"),
2810 diff->i_getLocationFull().c_str());
2811 }
2812
2813 Guid parentMachineRegistry;
2814 if (i_getFirstRegistryMachineId(parentMachineRegistry))
2815 {
2816 /* since this medium has been just created it isn't associated yet */
2817 diff->m->llRegistryIDs.push_back(parentMachineRegistry);
2818 alock.release();
2819 treeLock.release();
2820 diff->i_markRegistriesModified();
2821 treeLock.acquire();
2822 alock.acquire();
2823 }
2824
2825 alock.release();
2826 treeLock.release();
2827
2828 ComObjPtr<Progress> pProgress;
2829
2830 ULONG mediumVariantFlags = 0;
2831
2832 if (aVariant.size())
2833 {
2834 for (size_t i = 0; i < aVariant.size(); i++)
2835 mediumVariantFlags |= (ULONG)aVariant[i];
2836 }
2837
2838 rc = i_createDiffStorage(diff, (MediumVariant_T)mediumVariantFlags, pMediumLockList,
2839 &pProgress, false /* aWait */);
2840 if (FAILED(rc))
2841 delete pMediumLockList;
2842 else
2843 pProgress.queryInterfaceTo(aProgress.asOutParam());
2844
2845 return rc;
2846}
2847
2848HRESULT Medium::mergeTo(const ComPtr<IMedium> &aTarget,
2849 ComPtr<IProgress> &aProgress)
2850{
2851
2852 /** @todo r=klaus The code below needs to be double checked with regard
2853 * to lock order violations, it probably causes lock order issues related
2854 * to the AutoCaller usage. */
2855 IMedium *aT = aTarget;
2856
2857 ComAssertRet(aT != this, E_INVALIDARG);
2858
2859 ComObjPtr<Medium> pTarget = static_cast<Medium*>(aT);
2860
2861 bool fMergeForward = false;
2862 ComObjPtr<Medium> pParentForTarget;
2863 MediumLockList *pChildrenToReparent = NULL;
2864 MediumLockList *pMediumLockList = NULL;
2865
2866 HRESULT rc = S_OK;
2867
2868 rc = i_prepareMergeTo(pTarget, NULL, NULL, true, fMergeForward,
2869 pParentForTarget, pChildrenToReparent, pMediumLockList);
2870 if (FAILED(rc)) return rc;
2871
2872 ComObjPtr<Progress> pProgress;
2873
2874 rc = i_mergeTo(pTarget, fMergeForward, pParentForTarget, pChildrenToReparent,
2875 pMediumLockList, &pProgress, false /* aWait */);
2876 if (FAILED(rc))
2877 i_cancelMergeTo(pChildrenToReparent, pMediumLockList);
2878 else
2879 pProgress.queryInterfaceTo(aProgress.asOutParam());
2880
2881 return rc;
2882}
2883
2884HRESULT Medium::cloneToBase(const ComPtr<IMedium> &aTarget,
2885 const std::vector<MediumVariant_T> &aVariant,
2886 ComPtr<IProgress> &aProgress)
2887{
2888 int rc = S_OK;
2889
2890 rc = cloneTo(aTarget, aVariant, NULL, aProgress);
2891 return rc;
2892}
2893
2894HRESULT Medium::cloneTo(const ComPtr<IMedium> &aTarget,
2895 const std::vector<MediumVariant_T> &aVariant,
2896 const ComPtr<IMedium> &aParent,
2897 ComPtr<IProgress> &aProgress)
2898{
2899 /** @todo r=klaus The code below needs to be double checked with regard
2900 * to lock order violations, it probably causes lock order issues related
2901 * to the AutoCaller usage. */
2902 ComAssertRet(aTarget != this, E_INVALIDARG);
2903
2904 IMedium *aT = aTarget;
2905 ComObjPtr<Medium> pTarget = static_cast<Medium*>(aT);
2906 ComObjPtr<Medium> pParent;
2907 if (aParent)
2908 {
2909 IMedium *aP = aParent;
2910 pParent = static_cast<Medium*>(aP);
2911 }
2912
2913 HRESULT rc = S_OK;
2914 ComObjPtr<Progress> pProgress;
2915 Medium::Task *pTask = NULL;
2916
2917 try
2918 {
2919 // locking: we need the tree lock first because we access parent pointers
2920 // and we need to write-lock the media involved
2921 uint32_t cHandles = 3;
2922 LockHandle* pHandles[4] = { &m->pVirtualBox->i_getMediaTreeLockHandle(),
2923 this->lockHandle(),
2924 pTarget->lockHandle() };
2925 /* Only add parent to the lock if it is not null */
2926 if (!pParent.isNull())
2927 pHandles[cHandles++] = pParent->lockHandle();
2928 AutoWriteLock alock(cHandles,
2929 pHandles
2930 COMMA_LOCKVAL_SRC_POS);
2931
2932 if ( pTarget->m->state != MediumState_NotCreated
2933 && pTarget->m->state != MediumState_Created)
2934 throw pTarget->i_setStateError();
2935
2936 /* Build the source lock list. */
2937 MediumLockList *pSourceMediumLockList(new MediumLockList());
2938 alock.release();
2939 rc = i_createMediumLockList(true /* fFailIfInaccessible */,
2940 NULL /* pToLockWrite */,
2941 false /* fMediumLockWriteAll */,
2942 NULL,
2943 *pSourceMediumLockList);
2944 alock.acquire();
2945 if (FAILED(rc))
2946 {
2947 delete pSourceMediumLockList;
2948 throw rc;
2949 }
2950
2951 /* Build the target lock list (including the to-be parent chain). */
2952 MediumLockList *pTargetMediumLockList(new MediumLockList());
2953 alock.release();
2954 rc = pTarget->i_createMediumLockList(true /* fFailIfInaccessible */,
2955 pTarget /* pToLockWrite */,
2956 false /* fMediumLockWriteAll */,
2957 pParent,
2958 *pTargetMediumLockList);
2959 alock.acquire();
2960 if (FAILED(rc))
2961 {
2962 delete pSourceMediumLockList;
2963 delete pTargetMediumLockList;
2964 throw rc;
2965 }
2966
2967 alock.release();
2968 rc = pSourceMediumLockList->Lock();
2969 alock.acquire();
2970 if (FAILED(rc))
2971 {
2972 delete pSourceMediumLockList;
2973 delete pTargetMediumLockList;
2974 throw setError(rc,
2975 tr("Failed to lock source media '%s'"),
2976 i_getLocationFull().c_str());
2977 }
2978 alock.release();
2979 rc = pTargetMediumLockList->Lock();
2980 alock.acquire();
2981 if (FAILED(rc))
2982 {
2983 delete pSourceMediumLockList;
2984 delete pTargetMediumLockList;
2985 throw setError(rc,
2986 tr("Failed to lock target media '%s'"),
2987 pTarget->i_getLocationFull().c_str());
2988 }
2989
2990 pProgress.createObject();
2991 rc = pProgress->init(m->pVirtualBox,
2992 static_cast <IMedium *>(this),
2993 BstrFmt(tr("Creating clone medium '%s'"), pTarget->m->strLocationFull.c_str()).raw(),
2994 TRUE /* aCancelable */);
2995 if (FAILED(rc))
2996 {
2997 delete pSourceMediumLockList;
2998 delete pTargetMediumLockList;
2999 throw rc;
3000 }
3001
3002 ULONG mediumVariantFlags = 0;
3003
3004 if (aVariant.size())
3005 {
3006 for (size_t i = 0; i < aVariant.size(); i++)
3007 mediumVariantFlags |= (ULONG)aVariant[i];
3008 }
3009
3010 /* setup task object to carry out the operation asynchronously */
3011 pTask = new Medium::CloneTask(this, pProgress, pTarget,
3012 (MediumVariant_T)mediumVariantFlags,
3013 pParent, UINT32_MAX, UINT32_MAX,
3014 pSourceMediumLockList, pTargetMediumLockList);
3015 rc = pTask->rc();
3016 AssertComRC(rc);
3017 if (FAILED(rc))
3018 throw rc;
3019
3020 if (pTarget->m->state == MediumState_NotCreated)
3021 pTarget->m->state = MediumState_Creating;
3022 }
3023 catch (HRESULT aRC) { rc = aRC; }
3024
3025 if (SUCCEEDED(rc))
3026 {
3027 rc = pTask->createThread();
3028
3029 if (SUCCEEDED(rc))
3030 pProgress.queryInterfaceTo(aProgress.asOutParam());
3031 }
3032 else if (pTask != NULL)
3033 delete pTask;
3034
3035 return rc;
3036}
3037
3038HRESULT Medium::setLocation(const com::Utf8Str &aLocation, ComPtr<IProgress> &aProgress)
3039{
3040
3041 ComObjPtr<Medium> pParent;
3042 ComObjPtr<Progress> pProgress;
3043 HRESULT rc = S_OK;
3044 Medium::Task *pTask = NULL;
3045
3046 try
3047 {
3048 /// @todo NEWMEDIA for file names, add the default extension if no extension
3049 /// is present (using the information from the VD backend which also implies
3050 /// that one more parameter should be passed to setLocation() requesting
3051 /// that functionality since it is only allowed when called from this method
3052
3053 /// @todo NEWMEDIA rename the file and set m->location on success, then save
3054 /// the global registry (and local registries of portable VMs referring to
3055 /// this medium), this will also require to add the mRegistered flag to data
3056
3057 // locking: we need the tree lock first because we access parent pointers
3058 // and we need to write-lock the media involved
3059 uint32_t cHandles = 2;
3060 LockHandle* pHandles[2] = { &m->pVirtualBox->i_getMediaTreeLockHandle(),
3061 this->lockHandle() };
3062
3063 AutoWriteLock alock(cHandles,
3064 pHandles
3065 COMMA_LOCKVAL_SRC_POS);
3066
3067 /* play with locations */
3068 {
3069 /* get source path and filename */
3070 Utf8Str sourceMediumPath = i_getLocationFull();
3071 Utf8Str sourceMediumFileName = i_getName();
3072
3073 if (aLocation.isEmpty())
3074 {
3075 rc = setError(VERR_PATH_ZERO_LENGTH,
3076 tr("Medium '%s' can't be moved. Destination path is empty."),
3077 i_getLocationFull().c_str());
3078 throw rc;
3079 }
3080
3081 /* extract destination path and filename */
3082 Utf8Str destMediumPath(aLocation);
3083 Utf8Str destMediumFileName(destMediumPath);
3084 destMediumFileName.stripPath();
3085
3086 Utf8Str suffix(destMediumFileName);
3087 suffix.stripSuffix();
3088
3089 if (suffix.equals(destMediumFileName) && !destMediumFileName.isEmpty())
3090 {
3091 /*
3092 * small trick. This case means target path has no filename at the end.
3093 * it will look like "/path/to/new/location" or just "newname"
3094 * there is no backslash in the end
3095 * or there is no filename with extension(suffix) in the end
3096 */
3097
3098 /* case when new path contains only "newname", no path, no extension */
3099 if (destMediumPath.equals(destMediumFileName))
3100 {
3101 Utf8Str localSuffix = RTPathSuffix(sourceMediumFileName.c_str());
3102 destMediumFileName.append(localSuffix);
3103 destMediumPath = destMediumFileName;
3104 }
3105 else
3106 {
3107 /* new path looks like "/path/to/new/location" */
3108 destMediumFileName.setNull();
3109 destMediumPath.append(RTPATH_SLASH);
3110 }
3111 }
3112
3113 if (destMediumFileName.isEmpty())
3114 {
3115 /* No target name */
3116 destMediumPath.append(sourceMediumFileName);
3117 }
3118 else
3119 {
3120 if (destMediumPath.equals(destMediumFileName))
3121 {
3122 /*
3123 * the passed target path consist of only a filename without directory
3124 * next move medium within the source directory with the passed new name
3125 */
3126 destMediumPath = sourceMediumPath.stripFilename().append(RTPATH_SLASH).append(destMediumFileName);
3127 }
3128 suffix = i_getFormat();
3129
3130 if (suffix.compare("RAW", Utf8Str::CaseInsensitive) == 0)
3131 {
3132 if (i_getDeviceType() == DeviceType_DVD)
3133 suffix = "iso";
3134 else
3135 {
3136 rc = setError(VERR_NOT_A_FILE,
3137 tr("Medium '%s' has RAW type. \"Move\" operation isn't supported for this type."),
3138 i_getLocationFull().c_str());
3139 throw rc;
3140 }
3141 }
3142 /* set the target extension like on the source. Any conversions are prohibited */
3143 suffix.toLower();
3144 destMediumPath.stripSuffix().append('.').append(suffix);
3145 }
3146
3147 if (i_isMediumFormatFile())
3148 {
3149 /* Path must be absolute */
3150 char *pszAbs = RTPathAbsDup(destMediumPath.c_str());
3151 int iCmp = destMediumPath.compare(pszAbs, Utf8Str::CaseInsensitive);
3152 RTStrFree(pszAbs);
3153 if (iCmp)
3154 {
3155 rc = setError(VBOX_E_FILE_ERROR,
3156 tr("The given target path '%s' is not absolute"),
3157 destMediumPath.c_str());
3158 throw rc;
3159 }
3160 /* Check path for a new file object */
3161 rc = VirtualBox::i_ensureFilePathExists(destMediumPath, true);
3162 if (FAILED(rc))
3163 throw rc;
3164 }
3165 else
3166 {
3167 rc = setError(VERR_NOT_A_FILE,
3168 tr("Medium '%s' isn't a file object. \"Move\" operation isn't supported."),
3169 i_getLocationFull().c_str());
3170 throw rc;
3171 }
3172
3173 /* Set needed variables for "moving" procedure. It'll be used later in separate thread task */
3174 rc = i_preparationForMoving(destMediumPath);
3175 if (FAILED(rc))
3176 {
3177 rc = setError(VERR_NO_CHANGE,
3178 tr("Medium '%s' is already in the correct location"),
3179 i_getLocationFull().c_str());
3180 throw rc;
3181 }
3182 }
3183
3184 /* Check VMs which have this medium attached to*/
3185 std::vector<com::Guid> aMachineIds;
3186 rc = getMachineIds(aMachineIds);
3187 std::vector<com::Guid>::const_iterator currMachineID = aMachineIds.begin();
3188 std::vector<com::Guid>::const_iterator lastMachineID = aMachineIds.end();
3189
3190 while (currMachineID != lastMachineID)
3191 {
3192 Guid id(*currMachineID);
3193 ComObjPtr<Machine> aMachine;
3194
3195 alock.release();
3196 rc = m->pVirtualBox->i_findMachine(id, false, true, &aMachine);
3197 alock.acquire();
3198
3199 if (SUCCEEDED(rc))
3200 {
3201 ComObjPtr<SessionMachine> sm;
3202 ComPtr<IInternalSessionControl> ctl;
3203
3204 alock.release();
3205 bool ses = aMachine->i_isSessionOpenVM(sm, &ctl);
3206 alock.acquire();
3207
3208 if (ses)
3209 {
3210 rc = setError(VERR_VM_UNEXPECTED_VM_STATE,
3211 tr("At least VM '%s' to whom this medium '%s' attached has the opened session now. "
3212 "Stop all needed VM before set a new location."),
3213 id.toString().c_str(),
3214 i_getLocationFull().c_str());
3215 throw rc;
3216 }
3217 }
3218 ++currMachineID;
3219 }
3220
3221 /* Build the source lock list. */
3222 MediumLockList *pMediumLockList(new MediumLockList());
3223 alock.release();
3224 rc = i_createMediumLockList(true /* fFailIfInaccessible */,
3225 this /* pToLockWrite */,
3226 true /* fMediumLockWriteAll */,
3227 NULL,
3228 *pMediumLockList);
3229 alock.acquire();
3230 if (FAILED(rc))
3231 {
3232 delete pMediumLockList;
3233 throw setError(rc,
3234 tr("Failed to create medium lock list for '%s'"),
3235 i_getLocationFull().c_str());
3236 }
3237 alock.release();
3238 rc = pMediumLockList->Lock();
3239 alock.acquire();
3240 if (FAILED(rc))
3241 {
3242 delete pMediumLockList;
3243 throw setError(rc,
3244 tr("Failed to lock media '%s'"),
3245 i_getLocationFull().c_str());
3246 }
3247
3248 pProgress.createObject();
3249 rc = pProgress->init(m->pVirtualBox,
3250 static_cast <IMedium *>(this),
3251 BstrFmt(tr("Moving medium '%s'"), m->strLocationFull.c_str()).raw(),
3252 TRUE /* aCancelable */);
3253
3254 /* Do the disk moving. */
3255 if (SUCCEEDED(rc))
3256 {
3257 ULONG mediumVariantFlags = i_getVariant();
3258
3259 /* setup task object to carry out the operation asynchronously */
3260 pTask = new Medium::MoveTask(this, pProgress,
3261 (MediumVariant_T)mediumVariantFlags,
3262 pMediumLockList);
3263 rc = pTask->rc();
3264 AssertComRC(rc);
3265 if (FAILED(rc))
3266 throw rc;
3267 }
3268
3269 }
3270 catch (HRESULT aRC) { rc = aRC; }
3271
3272 if (SUCCEEDED(rc))
3273 {
3274 rc = pTask->createThread();
3275
3276 if (SUCCEEDED(rc))
3277 pProgress.queryInterfaceTo(aProgress.asOutParam());
3278 }
3279 else
3280 {
3281 if (pTask != NULL)
3282 delete pTask;
3283 }
3284
3285 return rc;
3286}
3287
3288HRESULT Medium::compact(ComPtr<IProgress> &aProgress)
3289{
3290 HRESULT rc = S_OK;
3291 ComObjPtr<Progress> pProgress;
3292 Medium::Task *pTask = NULL;
3293
3294 try
3295 {
3296 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3297
3298 /* Build the medium lock list. */
3299 MediumLockList *pMediumLockList(new MediumLockList());
3300 alock.release();
3301 rc = i_createMediumLockList(true /* fFailIfInaccessible */ ,
3302 this /* pToLockWrite */,
3303 false /* fMediumLockWriteAll */,
3304 NULL,
3305 *pMediumLockList);
3306 alock.acquire();
3307 if (FAILED(rc))
3308 {
3309 delete pMediumLockList;
3310 throw rc;
3311 }
3312
3313 alock.release();
3314 rc = pMediumLockList->Lock();
3315 alock.acquire();
3316 if (FAILED(rc))
3317 {
3318 delete pMediumLockList;
3319 throw setError(rc,
3320 tr("Failed to lock media when compacting '%s'"),
3321 i_getLocationFull().c_str());
3322 }
3323
3324 pProgress.createObject();
3325 rc = pProgress->init(m->pVirtualBox,
3326 static_cast <IMedium *>(this),
3327 BstrFmt(tr("Compacting medium '%s'"), m->strLocationFull.c_str()).raw(),
3328 TRUE /* aCancelable */);
3329 if (FAILED(rc))
3330 {
3331 delete pMediumLockList;
3332 throw rc;
3333 }
3334
3335 /* setup task object to carry out the operation asynchronously */
3336 pTask = new Medium::CompactTask(this, pProgress, pMediumLockList);
3337 rc = pTask->rc();
3338 AssertComRC(rc);
3339 if (FAILED(rc))
3340 throw rc;
3341 }
3342 catch (HRESULT aRC) { rc = aRC; }
3343
3344 if (SUCCEEDED(rc))
3345 {
3346 rc = pTask->createThread();
3347
3348 if (SUCCEEDED(rc))
3349 pProgress.queryInterfaceTo(aProgress.asOutParam());
3350 }
3351 else if (pTask != NULL)
3352 delete pTask;
3353
3354 return rc;
3355}
3356
3357HRESULT Medium::resize(LONG64 aLogicalSize,
3358 ComPtr<IProgress> &aProgress)
3359{
3360 HRESULT rc = S_OK;
3361 ComObjPtr<Progress> pProgress;
3362 Medium::Task *pTask = NULL;
3363
3364 try
3365 {
3366 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3367
3368 /* Build the medium lock list. */
3369 MediumLockList *pMediumLockList(new MediumLockList());
3370 alock.release();
3371 rc = i_createMediumLockList(true /* fFailIfInaccessible */ ,
3372 this /* pToLockWrite */,
3373 false /* fMediumLockWriteAll */,
3374 NULL,
3375 *pMediumLockList);
3376 alock.acquire();
3377 if (FAILED(rc))
3378 {
3379 delete pMediumLockList;
3380 throw rc;
3381 }
3382
3383 alock.release();
3384 rc = pMediumLockList->Lock();
3385 alock.acquire();
3386 if (FAILED(rc))
3387 {
3388 delete pMediumLockList;
3389 throw setError(rc,
3390 tr("Failed to lock media when compacting '%s'"),
3391 i_getLocationFull().c_str());
3392 }
3393
3394 pProgress.createObject();
3395 rc = pProgress->init(m->pVirtualBox,
3396 static_cast <IMedium *>(this),
3397 BstrFmt(tr("Compacting medium '%s'"), m->strLocationFull.c_str()).raw(),
3398 TRUE /* aCancelable */);
3399 if (FAILED(rc))
3400 {
3401 delete pMediumLockList;
3402 throw rc;
3403 }
3404
3405 /* setup task object to carry out the operation asynchronously */
3406 pTask = new Medium::ResizeTask(this, aLogicalSize, pProgress, pMediumLockList);
3407 rc = pTask->rc();
3408 AssertComRC(rc);
3409 if (FAILED(rc))
3410 throw rc;
3411 }
3412 catch (HRESULT aRC) { rc = aRC; }
3413
3414 if (SUCCEEDED(rc))
3415 {
3416 rc = pTask->createThread();
3417
3418 if (SUCCEEDED(rc))
3419 pProgress.queryInterfaceTo(aProgress.asOutParam());
3420 }
3421 else if (pTask != NULL)
3422 delete pTask;
3423
3424 return rc;
3425}
3426
3427HRESULT Medium::reset(AutoCaller &autoCaller, ComPtr<IProgress> &aProgress)
3428{
3429 HRESULT rc = S_OK;
3430 ComObjPtr<Progress> pProgress;
3431 Medium::Task *pTask = NULL;
3432
3433 try
3434 {
3435 autoCaller.release();
3436
3437 /* It is possible that some previous/concurrent uninit has already
3438 * cleared the pVirtualBox reference, see #uninit(). */
3439 ComObjPtr<VirtualBox> pVirtualBox(m->pVirtualBox);
3440
3441 /* canClose() needs the tree lock */
3442 AutoMultiWriteLock2 multilock(!pVirtualBox.isNull() ? &pVirtualBox->i_getMediaTreeLockHandle() : NULL,
3443 this->lockHandle()
3444 COMMA_LOCKVAL_SRC_POS);
3445
3446 autoCaller.add();
3447 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3448
3449 LogFlowThisFunc(("ENTER for medium %s\n", m->strLocationFull.c_str()));
3450
3451 if (m->pParent.isNull())
3452 throw setError(VBOX_E_NOT_SUPPORTED,
3453 tr("Medium type of '%s' is not differencing"),
3454 m->strLocationFull.c_str());
3455
3456 rc = i_canClose();
3457 if (FAILED(rc))
3458 throw rc;
3459
3460 /* Build the medium lock list. */
3461 MediumLockList *pMediumLockList(new MediumLockList());
3462 multilock.release();
3463 rc = i_createMediumLockList(true /* fFailIfInaccessible */,
3464 this /* pToLockWrite */,
3465 false /* fMediumLockWriteAll */,
3466 NULL,
3467 *pMediumLockList);
3468 multilock.acquire();
3469 if (FAILED(rc))
3470 {
3471 delete pMediumLockList;
3472 throw rc;
3473 }
3474
3475 multilock.release();
3476 rc = pMediumLockList->Lock();
3477 multilock.acquire();
3478 if (FAILED(rc))
3479 {
3480 delete pMediumLockList;
3481 throw setError(rc,
3482 tr("Failed to lock media when resetting '%s'"),
3483 i_getLocationFull().c_str());
3484 }
3485
3486 pProgress.createObject();
3487 rc = pProgress->init(m->pVirtualBox,
3488 static_cast<IMedium*>(this),
3489 BstrFmt(tr("Resetting differencing medium '%s'"), m->strLocationFull.c_str()).raw(),
3490 FALSE /* aCancelable */);
3491 if (FAILED(rc))
3492 throw rc;
3493
3494 /* setup task object to carry out the operation asynchronously */
3495 pTask = new Medium::ResetTask(this, pProgress, pMediumLockList);
3496 rc = pTask->rc();
3497 AssertComRC(rc);
3498 if (FAILED(rc))
3499 throw rc;
3500 }
3501 catch (HRESULT aRC) { rc = aRC; }
3502
3503 if (SUCCEEDED(rc))
3504 {
3505 rc = pTask->createThread();
3506
3507 if (SUCCEEDED(rc))
3508 pProgress.queryInterfaceTo(aProgress.asOutParam());
3509 }
3510 else if (pTask != NULL)
3511 delete pTask;
3512
3513 LogFlowThisFunc(("LEAVE, rc=%Rhrc\n", rc));
3514
3515 return rc;
3516}
3517
3518HRESULT Medium::changeEncryption(const com::Utf8Str &aCurrentPassword, const com::Utf8Str &aCipher,
3519 const com::Utf8Str &aNewPassword, const com::Utf8Str &aNewPasswordId,
3520 ComPtr<IProgress> &aProgress)
3521{
3522 HRESULT rc = S_OK;
3523 ComObjPtr<Progress> pProgress;
3524 Medium::Task *pTask = NULL;
3525
3526 try
3527 {
3528 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3529
3530 DeviceType_T devType = i_getDeviceType();
3531 /* Cannot encrypt DVD or floppy images so far. */
3532 if ( devType == DeviceType_DVD
3533 || devType == DeviceType_Floppy)
3534 return setError(VBOX_E_INVALID_OBJECT_STATE,
3535 tr("Cannot encrypt DVD or Floppy medium '%s'"),
3536 m->strLocationFull.c_str());
3537
3538 /* Cannot encrypt media which are attached to more than one virtual machine. */
3539 if (m->backRefs.size() > 1)
3540 return setError(VBOX_E_INVALID_OBJECT_STATE,
3541 tr("Cannot encrypt medium '%s' because it is attached to %d virtual machines"),
3542 m->strLocationFull.c_str(), m->backRefs.size());
3543
3544 if (i_getChildren().size() != 0)
3545 return setError(VBOX_E_INVALID_OBJECT_STATE,
3546 tr("Cannot encrypt medium '%s' because it has %d children"),
3547 m->strLocationFull.c_str(), i_getChildren().size());
3548
3549 /* Build the medium lock list. */
3550 MediumLockList *pMediumLockList(new MediumLockList());
3551 alock.release();
3552 rc = i_createMediumLockList(true /* fFailIfInaccessible */ ,
3553 this /* pToLockWrite */,
3554 true /* fMediumLockAllWrite */,
3555 NULL,
3556 *pMediumLockList);
3557 alock.acquire();
3558 if (FAILED(rc))
3559 {
3560 delete pMediumLockList;
3561 throw rc;
3562 }
3563
3564 alock.release();
3565 rc = pMediumLockList->Lock();
3566 alock.acquire();
3567 if (FAILED(rc))
3568 {
3569 delete pMediumLockList;
3570 throw setError(rc,
3571 tr("Failed to lock media for encryption '%s'"),
3572 i_getLocationFull().c_str());
3573 }
3574
3575 /*
3576 * Check all media in the chain to not contain any branches or references to
3577 * other virtual machines, we support encrypting only a list of differencing media at the moment.
3578 */
3579 MediumLockList::Base::const_iterator mediumListBegin = pMediumLockList->GetBegin();
3580 MediumLockList::Base::const_iterator mediumListEnd = pMediumLockList->GetEnd();
3581 for (MediumLockList::Base::const_iterator it = mediumListBegin;
3582 it != mediumListEnd;
3583 ++it)
3584 {
3585 const MediumLock &mediumLock = *it;
3586 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
3587 AutoReadLock mediumReadLock(pMedium COMMA_LOCKVAL_SRC_POS);
3588
3589 Assert(pMedium->m->state == MediumState_LockedWrite);
3590
3591 if (pMedium->m->backRefs.size() > 1)
3592 {
3593 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3594 tr("Cannot encrypt medium '%s' because it is attached to %d virtual machines"),
3595 pMedium->m->strLocationFull.c_str(), pMedium->m->backRefs.size());
3596 break;
3597 }
3598 else if (pMedium->i_getChildren().size() > 1)
3599 {
3600 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3601 tr("Cannot encrypt medium '%s' because it has %d children"),
3602 pMedium->m->strLocationFull.c_str(), pMedium->i_getChildren().size());
3603 break;
3604 }
3605 }
3606
3607 if (FAILED(rc))
3608 {
3609 delete pMediumLockList;
3610 throw rc;
3611 }
3612
3613 const char *pszAction = "Encrypting";
3614 if ( aCurrentPassword.isNotEmpty()
3615 && aCipher.isEmpty())
3616 pszAction = "Decrypting";
3617
3618 pProgress.createObject();
3619 rc = pProgress->init(m->pVirtualBox,
3620 static_cast <IMedium *>(this),
3621 BstrFmt(tr("%s medium '%s'"), pszAction, m->strLocationFull.c_str()).raw(),
3622 TRUE /* aCancelable */);
3623 if (FAILED(rc))
3624 {
3625 delete pMediumLockList;
3626 throw rc;
3627 }
3628
3629 /* setup task object to carry out the operation asynchronously */
3630 pTask = new Medium::EncryptTask(this, aNewPassword, aCurrentPassword,
3631 aCipher, aNewPasswordId, pProgress, pMediumLockList);
3632 rc = pTask->rc();
3633 AssertComRC(rc);
3634 if (FAILED(rc))
3635 throw rc;
3636 }
3637 catch (HRESULT aRC) { rc = aRC; }
3638
3639 if (SUCCEEDED(rc))
3640 {
3641 rc = pTask->createThread();
3642
3643 if (SUCCEEDED(rc))
3644 pProgress.queryInterfaceTo(aProgress.asOutParam());
3645 }
3646 else if (pTask != NULL)
3647 delete pTask;
3648
3649 return rc;
3650}
3651
3652HRESULT Medium::getEncryptionSettings(com::Utf8Str &aCipher, com::Utf8Str &aPasswordId)
3653{
3654#ifndef VBOX_WITH_EXTPACK
3655 RT_NOREF(aCipher, aPasswordId);
3656#endif
3657 HRESULT rc = S_OK;
3658
3659 try
3660 {
3661 ComObjPtr<Medium> pBase = i_getBase();
3662 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3663
3664 /* Check whether encryption is configured for this medium. */
3665 settings::StringsMap::iterator it = pBase->m->mapProperties.find("CRYPT/KeyStore");
3666 if (it == pBase->m->mapProperties.end())
3667 throw VBOX_E_NOT_SUPPORTED;
3668
3669# ifdef VBOX_WITH_EXTPACK
3670 ExtPackManager *pExtPackManager = m->pVirtualBox->i_getExtPackManager();
3671 if (pExtPackManager->i_isExtPackUsable(ORACLE_PUEL_EXTPACK_NAME))
3672 {
3673 /* Load the plugin */
3674 Utf8Str strPlugin;
3675 rc = pExtPackManager->i_getLibraryPathForExtPack(g_szVDPlugin, ORACLE_PUEL_EXTPACK_NAME, &strPlugin);
3676 if (SUCCEEDED(rc))
3677 {
3678 int vrc = VDPluginLoadFromFilename(strPlugin.c_str());
3679 if (RT_FAILURE(vrc))
3680 throw setError(VBOX_E_NOT_SUPPORTED,
3681 tr("Retrieving encryption settings of the image failed because the encryption plugin could not be loaded (%s)"),
3682 i_vdError(vrc).c_str());
3683 }
3684 else
3685 throw setError(VBOX_E_NOT_SUPPORTED,
3686 tr("Encryption is not supported because the extension pack '%s' is missing the encryption plugin (old extension pack installed?)"),
3687 ORACLE_PUEL_EXTPACK_NAME);
3688 }
3689 else
3690 throw setError(VBOX_E_NOT_SUPPORTED,
3691 tr("Encryption is not supported because the extension pack '%s' is missing"),
3692 ORACLE_PUEL_EXTPACK_NAME);
3693
3694 PVDISK pDisk = NULL;
3695 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &pDisk);
3696 ComAssertRCThrow(vrc, E_FAIL);
3697
3698 Medium::CryptoFilterSettings CryptoSettings;
3699
3700 i_taskEncryptSettingsSetup(&CryptoSettings, NULL, it->second.c_str(), NULL, false /* fCreateKeyStore */);
3701 vrc = VDFilterAdd(pDisk, "CRYPT", VD_FILTER_FLAGS_READ | VD_FILTER_FLAGS_INFO, CryptoSettings.vdFilterIfaces);
3702 if (RT_FAILURE(vrc))
3703 throw setError(VBOX_E_INVALID_OBJECT_STATE,
3704 tr("Failed to load the encryption filter: %s"),
3705 i_vdError(vrc).c_str());
3706
3707 it = pBase->m->mapProperties.find("CRYPT/KeyId");
3708 if (it == pBase->m->mapProperties.end())
3709 throw setError(VBOX_E_INVALID_OBJECT_STATE,
3710 tr("Image is configured for encryption but doesn't has a KeyId set"));
3711
3712 aPasswordId = it->second.c_str();
3713 aCipher = CryptoSettings.pszCipherReturned;
3714 RTStrFree(CryptoSettings.pszCipherReturned);
3715
3716 VDDestroy(pDisk);
3717# else
3718 throw setError(VBOX_E_NOT_SUPPORTED,
3719 tr("Encryption is not supported because extension pack support is not built in"));
3720# endif
3721 }
3722 catch (HRESULT aRC) { rc = aRC; }
3723
3724 return rc;
3725}
3726
3727HRESULT Medium::checkEncryptionPassword(const com::Utf8Str &aPassword)
3728{
3729 HRESULT rc = S_OK;
3730
3731 try
3732 {
3733 ComObjPtr<Medium> pBase = i_getBase();
3734 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3735
3736 settings::StringsMap::iterator it = pBase->m->mapProperties.find("CRYPT/KeyStore");
3737 if (it == pBase->m->mapProperties.end())
3738 throw setError(VBOX_E_NOT_SUPPORTED,
3739 tr("The image is not configured for encryption"));
3740
3741 if (aPassword.isEmpty())
3742 throw setError(E_INVALIDARG,
3743 tr("The given password must not be empty"));
3744
3745# ifdef VBOX_WITH_EXTPACK
3746 ExtPackManager *pExtPackManager = m->pVirtualBox->i_getExtPackManager();
3747 if (pExtPackManager->i_isExtPackUsable(ORACLE_PUEL_EXTPACK_NAME))
3748 {
3749 /* Load the plugin */
3750 Utf8Str strPlugin;
3751 rc = pExtPackManager->i_getLibraryPathForExtPack(g_szVDPlugin, ORACLE_PUEL_EXTPACK_NAME, &strPlugin);
3752 if (SUCCEEDED(rc))
3753 {
3754 int vrc = VDPluginLoadFromFilename(strPlugin.c_str());
3755 if (RT_FAILURE(vrc))
3756 throw setError(VBOX_E_NOT_SUPPORTED,
3757 tr("Retrieving encryption settings of the image failed because the encryption plugin could not be loaded (%s)"),
3758 i_vdError(vrc).c_str());
3759 }
3760 else
3761 throw setError(VBOX_E_NOT_SUPPORTED,
3762 tr("Encryption is not supported because the extension pack '%s' is missing the encryption plugin (old extension pack installed?)"),
3763 ORACLE_PUEL_EXTPACK_NAME);
3764 }
3765 else
3766 throw setError(VBOX_E_NOT_SUPPORTED,
3767 tr("Encryption is not supported because the extension pack '%s' is missing"),
3768 ORACLE_PUEL_EXTPACK_NAME);
3769
3770 PVDISK pDisk = NULL;
3771 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &pDisk);
3772 ComAssertRCThrow(vrc, E_FAIL);
3773
3774 Medium::CryptoFilterSettings CryptoSettings;
3775
3776 i_taskEncryptSettingsSetup(&CryptoSettings, NULL, it->second.c_str(), aPassword.c_str(),
3777 false /* fCreateKeyStore */);
3778 vrc = VDFilterAdd(pDisk, "CRYPT", VD_FILTER_FLAGS_READ, CryptoSettings.vdFilterIfaces);
3779 if (vrc == VERR_VD_PASSWORD_INCORRECT)
3780 throw setError(VBOX_E_PASSWORD_INCORRECT,
3781 tr("The given password is incorrect"));
3782 else if (RT_FAILURE(vrc))
3783 throw setError(VBOX_E_INVALID_OBJECT_STATE,
3784 tr("Failed to load the encryption filter: %s"),
3785 i_vdError(vrc).c_str());
3786
3787 VDDestroy(pDisk);
3788# else
3789 throw setError(VBOX_E_NOT_SUPPORTED,
3790 tr("Encryption is not supported because extension pack support is not built in"));
3791# endif
3792 }
3793 catch (HRESULT aRC) { rc = aRC; }
3794
3795 return rc;
3796}
3797
3798////////////////////////////////////////////////////////////////////////////////
3799//
3800// Medium public internal methods
3801//
3802////////////////////////////////////////////////////////////////////////////////
3803
3804/**
3805 * Internal method to return the medium's parent medium. Must have caller + locking!
3806 * @return
3807 */
3808const ComObjPtr<Medium>& Medium::i_getParent() const
3809{
3810 return m->pParent;
3811}
3812
3813/**
3814 * Internal method to return the medium's list of child media. Must have caller + locking!
3815 * @return
3816 */
3817const MediaList& Medium::i_getChildren() const
3818{
3819 return m->llChildren;
3820}
3821
3822/**
3823 * Internal method to return the medium's GUID. Must have caller + locking!
3824 * @return
3825 */
3826const Guid& Medium::i_getId() const
3827{
3828 return m->id;
3829}
3830
3831/**
3832 * Internal method to return the medium's state. Must have caller + locking!
3833 * @return
3834 */
3835MediumState_T Medium::i_getState() const
3836{
3837 return m->state;
3838}
3839
3840/**
3841 * Internal method to return the medium's variant. Must have caller + locking!
3842 * @return
3843 */
3844MediumVariant_T Medium::i_getVariant() const
3845{
3846 return m->variant;
3847}
3848
3849/**
3850 * Internal method which returns true if this medium represents a host drive.
3851 * @return
3852 */
3853bool Medium::i_isHostDrive() const
3854{
3855 return m->hostDrive;
3856}
3857
3858/**
3859 * Internal method to return the medium's full location. Must have caller + locking!
3860 * @return
3861 */
3862const Utf8Str& Medium::i_getLocationFull() const
3863{
3864 return m->strLocationFull;
3865}
3866
3867/**
3868 * Internal method to return the medium's format string. Must have caller + locking!
3869 * @return
3870 */
3871const Utf8Str& Medium::i_getFormat() const
3872{
3873 return m->strFormat;
3874}
3875
3876/**
3877 * Internal method to return the medium's format object. Must have caller + locking!
3878 * @return
3879 */
3880const ComObjPtr<MediumFormat>& Medium::i_getMediumFormat() const
3881{
3882 return m->formatObj;
3883}
3884
3885/**
3886 * Internal method that returns true if the medium is represented by a file on the host disk
3887 * (and not iSCSI or something).
3888 * @return
3889 */
3890bool Medium::i_isMediumFormatFile() const
3891{
3892 if ( m->formatObj
3893 && (m->formatObj->i_getCapabilities() & MediumFormatCapabilities_File)
3894 )
3895 return true;
3896 return false;
3897}
3898
3899/**
3900 * Internal method to return the medium's size. Must have caller + locking!
3901 * @return
3902 */
3903uint64_t Medium::i_getSize() const
3904{
3905 return m->size;
3906}
3907
3908/**
3909 * Returns the medium device type. Must have caller + locking!
3910 * @return
3911 */
3912DeviceType_T Medium::i_getDeviceType() const
3913{
3914 return m->devType;
3915}
3916
3917/**
3918 * Returns the medium type. Must have caller + locking!
3919 * @return
3920 */
3921MediumType_T Medium::i_getType() const
3922{
3923 return m->type;
3924}
3925
3926/**
3927 * Returns a short version of the location attribute.
3928 *
3929 * @note Must be called from under this object's read or write lock.
3930 */
3931Utf8Str Medium::i_getName()
3932{
3933 Utf8Str name = RTPathFilename(m->strLocationFull.c_str());
3934 return name;
3935}
3936
3937/**
3938 * This adds the given UUID to the list of media registries in which this
3939 * medium should be registered. The UUID can either be a machine UUID,
3940 * to add a machine registry, or the global registry UUID as returned by
3941 * VirtualBox::getGlobalRegistryId().
3942 *
3943 * Note that for hard disks, this method does nothing if the medium is
3944 * already in another registry to avoid having hard disks in more than
3945 * one registry, which causes trouble with keeping diff images in sync.
3946 * See getFirstRegistryMachineId() for details.
3947 *
3948 * @param id
3949 * @return true if the registry was added; false if the given id was already on the list.
3950 */
3951bool Medium::i_addRegistry(const Guid& id)
3952{
3953 AutoCaller autoCaller(this);
3954 if (FAILED(autoCaller.rc()))
3955 return false;
3956 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3957
3958 bool fAdd = true;
3959
3960 // hard disks cannot be in more than one registry
3961 if ( m->devType == DeviceType_HardDisk
3962 && m->llRegistryIDs.size() > 0)
3963 fAdd = false;
3964
3965 // no need to add the UUID twice
3966 if (fAdd)
3967 {
3968 for (GuidList::const_iterator it = m->llRegistryIDs.begin();
3969 it != m->llRegistryIDs.end();
3970 ++it)
3971 {
3972 if ((*it) == id)
3973 {
3974 fAdd = false;
3975 break;
3976 }
3977 }
3978 }
3979
3980 if (fAdd)
3981 m->llRegistryIDs.push_back(id);
3982
3983 return fAdd;
3984}
3985
3986/**
3987 * This adds the given UUID to the list of media registries in which this
3988 * medium should be registered. The UUID can either be a machine UUID,
3989 * to add a machine registry, or the global registry UUID as returned by
3990 * VirtualBox::getGlobalRegistryId(). This recurses over all children.
3991 *
3992 * Note that for hard disks, this method does nothing if the medium is
3993 * already in another registry to avoid having hard disks in more than
3994 * one registry, which causes trouble with keeping diff images in sync.
3995 * See getFirstRegistryMachineId() for details.
3996 *
3997 * @note the caller must hold the media tree lock for reading.
3998 *
3999 * @param id
4000 * @return true if the registry was added; false if the given id was already on the list.
4001 */
4002bool Medium::i_addRegistryRecursive(const Guid &id)
4003{
4004 AutoCaller autoCaller(this);
4005 if (FAILED(autoCaller.rc()))
4006 return false;
4007
4008 bool fAdd = i_addRegistry(id);
4009
4010 // protected by the medium tree lock held by our original caller
4011 for (MediaList::const_iterator it = i_getChildren().begin();
4012 it != i_getChildren().end();
4013 ++it)
4014 {
4015 Medium *pChild = *it;
4016 fAdd |= pChild->i_addRegistryRecursive(id);
4017 }
4018
4019 return fAdd;
4020}
4021
4022/**
4023 * Removes the given UUID from the list of media registry UUIDs of this medium.
4024 *
4025 * @param id
4026 * @return true if the UUID was found or false if not.
4027 */
4028bool Medium::i_removeRegistry(const Guid &id)
4029{
4030 AutoCaller autoCaller(this);
4031 if (FAILED(autoCaller.rc()))
4032 return false;
4033 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4034
4035 bool fRemove = false;
4036
4037 /// @todo r=klaus eliminate this code, replace it by using find.
4038 for (GuidList::iterator it = m->llRegistryIDs.begin();
4039 it != m->llRegistryIDs.end();
4040 ++it)
4041 {
4042 if ((*it) == id)
4043 {
4044 // getting away with this as the iterator isn't used after
4045 m->llRegistryIDs.erase(it);
4046 fRemove = true;
4047 break;
4048 }
4049 }
4050
4051 return fRemove;
4052}
4053
4054/**
4055 * Removes the given UUID from the list of media registry UUIDs, for this
4056 * medium and all its children recursively.
4057 *
4058 * @note the caller must hold the media tree lock for reading.
4059 *
4060 * @param id
4061 * @return true if the UUID was found or false if not.
4062 */
4063bool Medium::i_removeRegistryRecursive(const Guid &id)
4064{
4065 AutoCaller autoCaller(this);
4066 if (FAILED(autoCaller.rc()))
4067 return false;
4068
4069 bool fRemove = i_removeRegistry(id);
4070
4071 // protected by the medium tree lock held by our original caller
4072 for (MediaList::const_iterator it = i_getChildren().begin();
4073 it != i_getChildren().end();
4074 ++it)
4075 {
4076 Medium *pChild = *it;
4077 fRemove |= pChild->i_removeRegistryRecursive(id);
4078 }
4079
4080 return fRemove;
4081}
4082
4083/**
4084 * Returns true if id is in the list of media registries for this medium.
4085 *
4086 * Must have caller + read locking!
4087 *
4088 * @param id
4089 * @return
4090 */
4091bool Medium::i_isInRegistry(const Guid &id)
4092{
4093 /// @todo r=klaus eliminate this code, replace it by using find.
4094 for (GuidList::const_iterator it = m->llRegistryIDs.begin();
4095 it != m->llRegistryIDs.end();
4096 ++it)
4097 {
4098 if (*it == id)
4099 return true;
4100 }
4101
4102 return false;
4103}
4104
4105/**
4106 * Internal method to return the medium's first registry machine (i.e. the machine in whose
4107 * machine XML this medium is listed).
4108 *
4109 * Every attached medium must now (4.0) reside in at least one media registry, which is identified
4110 * by a UUID. This is either a machine UUID if the machine is from 4.0 or newer, in which case
4111 * machines have their own media registries, or it is the pseudo-UUID of the VirtualBox
4112 * object if the machine is old and still needs the global registry in VirtualBox.xml.
4113 *
4114 * By definition, hard disks may only be in one media registry, in which all its children
4115 * will be stored as well. Otherwise we run into problems with having keep multiple registries
4116 * in sync. (This is the "cloned VM" case in which VM1 may link to the disks of VM2; in this
4117 * case, only VM2's registry is used for the disk in question.)
4118 *
4119 * If there is no medium registry, particularly if the medium has not been attached yet, this
4120 * does not modify uuid and returns false.
4121 *
4122 * ISOs and RAWs, by contrast, can be in more than one repository to make things easier for
4123 * the user.
4124 *
4125 * Must have caller + locking!
4126 *
4127 * @param uuid Receives first registry machine UUID, if available.
4128 * @return true if uuid was set.
4129 */
4130bool Medium::i_getFirstRegistryMachineId(Guid &uuid) const
4131{
4132 if (m->llRegistryIDs.size())
4133 {
4134 uuid = m->llRegistryIDs.front();
4135 return true;
4136 }
4137 return false;
4138}
4139
4140/**
4141 * Marks all the registries in which this medium is registered as modified.
4142 */
4143void Medium::i_markRegistriesModified()
4144{
4145 AutoCaller autoCaller(this);
4146 if (FAILED(autoCaller.rc())) return;
4147
4148 // Get local copy, as keeping the lock over VirtualBox::markRegistryModified
4149 // causes trouble with the lock order
4150 GuidList llRegistryIDs;
4151 {
4152 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4153 llRegistryIDs = m->llRegistryIDs;
4154 }
4155
4156 autoCaller.release();
4157
4158 /* Save the error information now, the implicit restore when this goes
4159 * out of scope will throw away spurious additional errors created below. */
4160 ErrorInfoKeeper eik;
4161 for (GuidList::const_iterator it = llRegistryIDs.begin();
4162 it != llRegistryIDs.end();
4163 ++it)
4164 {
4165 m->pVirtualBox->i_markRegistryModified(*it);
4166 }
4167}
4168
4169/**
4170 * Adds the given machine and optionally the snapshot to the list of the objects
4171 * this medium is attached to.
4172 *
4173 * @param aMachineId Machine ID.
4174 * @param aSnapshotId Snapshot ID; when non-empty, adds a snapshot attachment.
4175 */
4176HRESULT Medium::i_addBackReference(const Guid &aMachineId,
4177 const Guid &aSnapshotId /*= Guid::Empty*/)
4178{
4179 AssertReturn(aMachineId.isValid(), E_FAIL);
4180
4181 LogFlowThisFunc(("ENTER, aMachineId: {%RTuuid}, aSnapshotId: {%RTuuid}\n", aMachineId.raw(), aSnapshotId.raw()));
4182
4183 AutoCaller autoCaller(this);
4184 AssertComRCReturnRC(autoCaller.rc());
4185
4186 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4187
4188 switch (m->state)
4189 {
4190 case MediumState_Created:
4191 case MediumState_Inaccessible:
4192 case MediumState_LockedRead:
4193 case MediumState_LockedWrite:
4194 break;
4195
4196 default:
4197 return i_setStateError();
4198 }
4199
4200 if (m->numCreateDiffTasks > 0)
4201 return setError(VBOX_E_OBJECT_IN_USE,
4202 tr("Cannot attach medium '%s' {%RTuuid}: %u differencing child media are being created"),
4203 m->strLocationFull.c_str(),
4204 m->id.raw(),
4205 m->numCreateDiffTasks);
4206
4207 BackRefList::iterator it = std::find_if(m->backRefs.begin(),
4208 m->backRefs.end(),
4209 BackRef::EqualsTo(aMachineId));
4210 if (it == m->backRefs.end())
4211 {
4212 BackRef ref(aMachineId, aSnapshotId);
4213 m->backRefs.push_back(ref);
4214
4215 return S_OK;
4216 }
4217
4218 // if the caller has not supplied a snapshot ID, then we're attaching
4219 // to a machine a medium which represents the machine's current state,
4220 // so set the flag
4221
4222 if (aSnapshotId.isZero())
4223 {
4224 /* sanity: no duplicate attachments */
4225 if (it->fInCurState)
4226 return setError(VBOX_E_OBJECT_IN_USE,
4227 tr("Cannot attach medium '%s' {%RTuuid}: medium is already associated with the current state of machine uuid {%RTuuid}!"),
4228 m->strLocationFull.c_str(),
4229 m->id.raw(),
4230 aMachineId.raw());
4231 it->fInCurState = true;
4232
4233 return S_OK;
4234 }
4235
4236 // otherwise: a snapshot medium is being attached
4237
4238 /* sanity: no duplicate attachments */
4239 for (GuidList::const_iterator jt = it->llSnapshotIds.begin();
4240 jt != it->llSnapshotIds.end();
4241 ++jt)
4242 {
4243 const Guid &idOldSnapshot = *jt;
4244
4245 if (idOldSnapshot == aSnapshotId)
4246 {
4247#ifdef DEBUG
4248 i_dumpBackRefs();
4249#endif
4250 return setError(VBOX_E_OBJECT_IN_USE,
4251 tr("Cannot attach medium '%s' {%RTuuid} from snapshot '%RTuuid': medium is already in use by this snapshot!"),
4252 m->strLocationFull.c_str(),
4253 m->id.raw(),
4254 aSnapshotId.raw());
4255 }
4256 }
4257
4258 it->llSnapshotIds.push_back(aSnapshotId);
4259 // Do not touch fInCurState, as the image may be attached to the current
4260 // state *and* a snapshot, otherwise we lose the current state association!
4261
4262 LogFlowThisFuncLeave();
4263
4264 return S_OK;
4265}
4266
4267/**
4268 * Removes the given machine and optionally the snapshot from the list of the
4269 * objects this medium is attached to.
4270 *
4271 * @param aMachineId Machine ID.
4272 * @param aSnapshotId Snapshot ID; when non-empty, removes the snapshot
4273 * attachment.
4274 */
4275HRESULT Medium::i_removeBackReference(const Guid &aMachineId,
4276 const Guid &aSnapshotId /*= Guid::Empty*/)
4277{
4278 AssertReturn(aMachineId.isValid(), E_FAIL);
4279
4280 AutoCaller autoCaller(this);
4281 AssertComRCReturnRC(autoCaller.rc());
4282
4283 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4284
4285 BackRefList::iterator it =
4286 std::find_if(m->backRefs.begin(), m->backRefs.end(),
4287 BackRef::EqualsTo(aMachineId));
4288 AssertReturn(it != m->backRefs.end(), E_FAIL);
4289
4290 if (aSnapshotId.isZero())
4291 {
4292 /* remove the current state attachment */
4293 it->fInCurState = false;
4294 }
4295 else
4296 {
4297 /* remove the snapshot attachment */
4298 GuidList::iterator jt = std::find(it->llSnapshotIds.begin(),
4299 it->llSnapshotIds.end(),
4300 aSnapshotId);
4301
4302 AssertReturn(jt != it->llSnapshotIds.end(), E_FAIL);
4303 it->llSnapshotIds.erase(jt);
4304 }
4305
4306 /* if the backref becomes empty, remove it */
4307 if (it->fInCurState == false && it->llSnapshotIds.size() == 0)
4308 m->backRefs.erase(it);
4309
4310 return S_OK;
4311}
4312
4313/**
4314 * Internal method to return the medium's list of backrefs. Must have caller + locking!
4315 * @return
4316 */
4317const Guid* Medium::i_getFirstMachineBackrefId() const
4318{
4319 if (!m->backRefs.size())
4320 return NULL;
4321
4322 return &m->backRefs.front().machineId;
4323}
4324
4325/**
4326 * Internal method which returns a machine that either this medium or one of its children
4327 * is attached to. This is used for finding a replacement media registry when an existing
4328 * media registry is about to be deleted in VirtualBox::unregisterMachine().
4329 *
4330 * Must have caller + locking, *and* caller must hold the media tree lock!
4331 * @return
4332 */
4333const Guid* Medium::i_getAnyMachineBackref() const
4334{
4335 if (m->backRefs.size())
4336 return &m->backRefs.front().machineId;
4337
4338 for (MediaList::const_iterator it = i_getChildren().begin();
4339 it != i_getChildren().end();
4340 ++it)
4341 {
4342 Medium *pChild = *it;
4343 // recurse for this child
4344 const Guid* puuid;
4345 if ((puuid = pChild->i_getAnyMachineBackref()))
4346 return puuid;
4347 }
4348
4349 return NULL;
4350}
4351
4352const Guid* Medium::i_getFirstMachineBackrefSnapshotId() const
4353{
4354 if (!m->backRefs.size())
4355 return NULL;
4356
4357 const BackRef &ref = m->backRefs.front();
4358 if (ref.llSnapshotIds.empty())
4359 return NULL;
4360
4361 return &ref.llSnapshotIds.front();
4362}
4363
4364size_t Medium::i_getMachineBackRefCount() const
4365{
4366 return m->backRefs.size();
4367}
4368
4369#ifdef DEBUG
4370/**
4371 * Debugging helper that gets called after VirtualBox initialization that writes all
4372 * machine backreferences to the debug log.
4373 */
4374void Medium::i_dumpBackRefs()
4375{
4376 AutoCaller autoCaller(this);
4377 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4378
4379 LogFlowThisFunc(("Dumping backrefs for medium '%s':\n", m->strLocationFull.c_str()));
4380
4381 for (BackRefList::iterator it2 = m->backRefs.begin();
4382 it2 != m->backRefs.end();
4383 ++it2)
4384 {
4385 const BackRef &ref = *it2;
4386 LogFlowThisFunc((" Backref from machine {%RTuuid} (fInCurState: %d)\n", ref.machineId.raw(), ref.fInCurState));
4387
4388 for (GuidList::const_iterator jt2 = it2->llSnapshotIds.begin();
4389 jt2 != it2->llSnapshotIds.end();
4390 ++jt2)
4391 {
4392 const Guid &id = *jt2;
4393 LogFlowThisFunc((" Backref from snapshot {%RTuuid}\n", id.raw()));
4394 }
4395 }
4396}
4397#endif
4398
4399/**
4400 * Checks if the given change of \a aOldPath to \a aNewPath affects the location
4401 * of this media and updates it if necessary to reflect the new location.
4402 *
4403 * @param strOldPath Old path (full).
4404 * @param strNewPath New path (full).
4405 *
4406 * @note Locks this object for writing.
4407 */
4408HRESULT Medium::i_updatePath(const Utf8Str &strOldPath, const Utf8Str &strNewPath)
4409{
4410 AssertReturn(!strOldPath.isEmpty(), E_FAIL);
4411 AssertReturn(!strNewPath.isEmpty(), E_FAIL);
4412
4413 AutoCaller autoCaller(this);
4414 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4415
4416 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4417
4418 LogFlowThisFunc(("locationFull.before='%s'\n", m->strLocationFull.c_str()));
4419
4420 const char *pcszMediumPath = m->strLocationFull.c_str();
4421
4422 if (RTPathStartsWith(pcszMediumPath, strOldPath.c_str()))
4423 {
4424 Utf8Str newPath(strNewPath);
4425 newPath.append(pcszMediumPath + strOldPath.length());
4426 unconst(m->strLocationFull) = newPath;
4427
4428 LogFlowThisFunc(("locationFull.after='%s'\n", m->strLocationFull.c_str()));
4429 // we changed something
4430 return S_OK;
4431 }
4432
4433 // no change was necessary, signal error which the caller needs to interpret
4434 return VBOX_E_FILE_ERROR;
4435}
4436
4437/**
4438 * Returns the base medium of the media chain this medium is part of.
4439 *
4440 * The base medium is found by walking up the parent-child relationship axis.
4441 * If the medium doesn't have a parent (i.e. it's a base medium), it
4442 * returns itself in response to this method.
4443 *
4444 * @param aLevel Where to store the number of ancestors of this medium
4445 * (zero for the base), may be @c NULL.
4446 *
4447 * @note Locks medium tree for reading.
4448 */
4449ComObjPtr<Medium> Medium::i_getBase(uint32_t *aLevel /*= NULL*/)
4450{
4451 ComObjPtr<Medium> pBase;
4452
4453 /* it is possible that some previous/concurrent uninit has already cleared
4454 * the pVirtualBox reference, and in this case we don't need to continue */
4455 ComObjPtr<VirtualBox> pVirtualBox(m->pVirtualBox);
4456 if (!pVirtualBox)
4457 return pBase;
4458
4459 /* we access m->pParent */
4460 AutoReadLock treeLock(pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4461
4462 AutoCaller autoCaller(this);
4463 AssertReturn(autoCaller.isOk(), pBase);
4464
4465 pBase = this;
4466 uint32_t level = 0;
4467
4468 if (m->pParent)
4469 {
4470 for (;;)
4471 {
4472 AutoCaller baseCaller(pBase);
4473 AssertReturn(baseCaller.isOk(), pBase);
4474
4475 if (pBase->m->pParent.isNull())
4476 break;
4477
4478 pBase = pBase->m->pParent;
4479 ++level;
4480 }
4481 }
4482
4483 if (aLevel != NULL)
4484 *aLevel = level;
4485
4486 return pBase;
4487}
4488
4489/**
4490 * Returns the depth of this medium in the media chain.
4491 *
4492 * @note Locks medium tree for reading.
4493 */
4494uint32_t Medium::i_getDepth()
4495{
4496 /* it is possible that some previous/concurrent uninit has already cleared
4497 * the pVirtualBox reference, and in this case we don't need to continue */
4498 ComObjPtr<VirtualBox> pVirtualBox(m->pVirtualBox);
4499 if (!pVirtualBox)
4500 return 1;
4501
4502 /* we access m->pParent */
4503 AutoReadLock treeLock(pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4504
4505 uint32_t cDepth = 0;
4506 ComObjPtr<Medium> pMedium(this);
4507 while (!pMedium.isNull())
4508 {
4509 AutoCaller autoCaller(this);
4510 AssertReturn(autoCaller.isOk(), cDepth + 1);
4511
4512 pMedium = pMedium->m->pParent;
4513 cDepth++;
4514 }
4515
4516 return cDepth;
4517}
4518
4519/**
4520 * Returns @c true if this medium cannot be modified because it has
4521 * dependents (children) or is part of the snapshot. Related to the medium
4522 * type and posterity, not to the current media state.
4523 *
4524 * @note Locks this object and medium tree for reading.
4525 */
4526bool Medium::i_isReadOnly()
4527{
4528 /* it is possible that some previous/concurrent uninit has already cleared
4529 * the pVirtualBox reference, and in this case we don't need to continue */
4530 ComObjPtr<VirtualBox> pVirtualBox(m->pVirtualBox);
4531 if (!pVirtualBox)
4532 return false;
4533
4534 /* we access children */
4535 AutoReadLock treeLock(m->pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4536
4537 AutoCaller autoCaller(this);
4538 AssertComRCReturn(autoCaller.rc(), false);
4539
4540 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4541
4542 switch (m->type)
4543 {
4544 case MediumType_Normal:
4545 {
4546 if (i_getChildren().size() != 0)
4547 return true;
4548
4549 for (BackRefList::const_iterator it = m->backRefs.begin();
4550 it != m->backRefs.end(); ++it)
4551 if (it->llSnapshotIds.size() != 0)
4552 return true;
4553
4554 if (m->variant & MediumVariant_VmdkStreamOptimized)
4555 return true;
4556
4557 return false;
4558 }
4559 case MediumType_Immutable:
4560 case MediumType_MultiAttach:
4561 return true;
4562 case MediumType_Writethrough:
4563 case MediumType_Shareable:
4564 case MediumType_Readonly: /* explicit readonly media has no diffs */
4565 return false;
4566 default:
4567 break;
4568 }
4569
4570 AssertFailedReturn(false);
4571}
4572
4573/**
4574 * Internal method to return the medium's size. Must have caller + locking!
4575 * @return
4576 */
4577void Medium::i_updateId(const Guid &id)
4578{
4579 unconst(m->id) = id;
4580}
4581
4582/**
4583 * Saves the settings of one medium.
4584 *
4585 * @note Caller MUST take care of the medium tree lock and caller.
4586 *
4587 * @param data Settings struct to be updated.
4588 * @param strHardDiskFolder Folder for which paths should be relative.
4589 */
4590void Medium::i_saveSettingsOne(settings::Medium &data, const Utf8Str &strHardDiskFolder)
4591{
4592 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4593
4594 data.uuid = m->id;
4595
4596 // make path relative if needed
4597 if ( !strHardDiskFolder.isEmpty()
4598 && RTPathStartsWith(m->strLocationFull.c_str(), strHardDiskFolder.c_str())
4599 )
4600 data.strLocation = m->strLocationFull.substr(strHardDiskFolder.length() + 1);
4601 else
4602 data.strLocation = m->strLocationFull;
4603 data.strFormat = m->strFormat;
4604
4605 /* optional, only for diffs, default is false */
4606 if (m->pParent)
4607 data.fAutoReset = m->autoReset;
4608 else
4609 data.fAutoReset = false;
4610
4611 /* optional */
4612 data.strDescription = m->strDescription;
4613
4614 /* optional properties */
4615 data.properties.clear();
4616
4617 /* handle iSCSI initiator secrets transparently */
4618 bool fHaveInitiatorSecretEncrypted = false;
4619 Utf8Str strCiphertext;
4620 settings::StringsMap::const_iterator itPln = m->mapProperties.find("InitiatorSecret");
4621 if ( itPln != m->mapProperties.end()
4622 && !itPln->second.isEmpty())
4623 {
4624 /* Encrypt the plain secret. If that does not work (i.e. no or wrong settings key
4625 * specified), just use the encrypted secret (if there is any). */
4626 int rc = m->pVirtualBox->i_encryptSetting(itPln->second, &strCiphertext);
4627 if (RT_SUCCESS(rc))
4628 fHaveInitiatorSecretEncrypted = true;
4629 }
4630 for (settings::StringsMap::const_iterator it = m->mapProperties.begin();
4631 it != m->mapProperties.end();
4632 ++it)
4633 {
4634 /* only save properties that have non-default values */
4635 if (!it->second.isEmpty())
4636 {
4637 const Utf8Str &name = it->first;
4638 const Utf8Str &value = it->second;
4639 /* do NOT store the plain InitiatorSecret */
4640 if ( !fHaveInitiatorSecretEncrypted
4641 || !name.equals("InitiatorSecret"))
4642 data.properties[name] = value;
4643 }
4644 }
4645 if (fHaveInitiatorSecretEncrypted)
4646 data.properties["InitiatorSecretEncrypted"] = strCiphertext;
4647
4648 /* only for base media */
4649 if (m->pParent.isNull())
4650 data.hdType = m->type;
4651}
4652
4653/**
4654 * Saves medium data by putting it into the provided data structure.
4655 * Recurses over all children to save their settings, too.
4656 *
4657 * @param data Settings struct to be updated.
4658 * @param strHardDiskFolder Folder for which paths should be relative.
4659 *
4660 * @note Locks this object, medium tree and children for reading.
4661 */
4662HRESULT Medium::i_saveSettings(settings::Medium &data,
4663 const Utf8Str &strHardDiskFolder)
4664{
4665 /* we access m->pParent */
4666 AutoReadLock treeLock(m->pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4667
4668 AutoCaller autoCaller(this);
4669 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4670
4671 i_saveSettingsOne(data, strHardDiskFolder);
4672
4673 /* save all children */
4674 settings::MediaList &llSettingsChildren = data.llChildren;
4675 for (MediaList::const_iterator it = i_getChildren().begin();
4676 it != i_getChildren().end();
4677 ++it)
4678 {
4679 // Use the element straight in the list to reduce both unnecessary
4680 // deep copying (when unwinding the recursion the entire medium
4681 // settings sub-tree is copied) and the stack footprint (the settings
4682 // need almost 1K, and there can be VMs with long image chains.
4683 llSettingsChildren.push_back(settings::Medium::Empty);
4684 HRESULT rc = (*it)->i_saveSettings(llSettingsChildren.back(), strHardDiskFolder);
4685 if (FAILED(rc))
4686 {
4687 llSettingsChildren.pop_back();
4688 return rc;
4689 }
4690 }
4691
4692 return S_OK;
4693}
4694
4695/**
4696 * Constructs a medium lock list for this medium. The lock is not taken.
4697 *
4698 * @note Caller MUST NOT hold the media tree or medium lock.
4699 *
4700 * @param fFailIfInaccessible If true, this fails with an error if a medium is inaccessible. If false,
4701 * inaccessible media are silently skipped and not locked (i.e. their state remains "Inaccessible");
4702 * this is necessary for a VM's removable media VM startup for which we do not want to fail.
4703 * @param pToLockWrite If not NULL, associate a write lock with this medium object.
4704 * @param fMediumLockWriteAll Whether to associate a write lock to all other media too.
4705 * @param pToBeParent Medium which will become the parent of this medium.
4706 * @param mediumLockList Where to store the resulting list.
4707 */
4708HRESULT Medium::i_createMediumLockList(bool fFailIfInaccessible,
4709 Medium *pToLockWrite,
4710 bool fMediumLockWriteAll,
4711 Medium *pToBeParent,
4712 MediumLockList &mediumLockList)
4713{
4714 /** @todo r=klaus this needs to be reworked, as the code below uses
4715 * i_getParent without holding the tree lock, and changing this is
4716 * a significant amount of effort. */
4717 Assert(!m->pVirtualBox->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4718 Assert(!isWriteLockOnCurrentThread());
4719
4720 AutoCaller autoCaller(this);
4721 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4722
4723 HRESULT rc = S_OK;
4724
4725 /* paranoid sanity checking if the medium has a to-be parent medium */
4726 if (pToBeParent)
4727 {
4728 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4729 ComAssertRet(i_getParent().isNull(), E_FAIL);
4730 ComAssertRet(i_getChildren().size() == 0, E_FAIL);
4731 }
4732
4733 ErrorInfoKeeper eik;
4734 MultiResult mrc(S_OK);
4735
4736 ComObjPtr<Medium> pMedium = this;
4737 while (!pMedium.isNull())
4738 {
4739 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
4740
4741 /* Accessibility check must be first, otherwise locking interferes
4742 * with getting the medium state. Lock lists are not created for
4743 * fun, and thus getting the medium status is no luxury. */
4744 MediumState_T mediumState = pMedium->i_getState();
4745 if (mediumState == MediumState_Inaccessible)
4746 {
4747 alock.release();
4748 rc = pMedium->i_queryInfo(false /* fSetImageId */, false /* fSetParentId */,
4749 autoCaller);
4750 alock.acquire();
4751 if (FAILED(rc)) return rc;
4752
4753 mediumState = pMedium->i_getState();
4754 if (mediumState == MediumState_Inaccessible)
4755 {
4756 // ignore inaccessible ISO media and silently return S_OK,
4757 // otherwise VM startup (esp. restore) may fail without good reason
4758 if (!fFailIfInaccessible)
4759 return S_OK;
4760
4761 // otherwise report an error
4762 Bstr error;
4763 rc = pMedium->COMGETTER(LastAccessError)(error.asOutParam());
4764 if (FAILED(rc)) return rc;
4765
4766 /* collect multiple errors */
4767 eik.restore();
4768 Assert(!error.isEmpty());
4769 mrc = setError(E_FAIL,
4770 "%ls",
4771 error.raw());
4772 // error message will be something like
4773 // "Could not open the medium ... VD: error VERR_FILE_NOT_FOUND opening image file ... (VERR_FILE_NOT_FOUND).
4774 eik.fetch();
4775 }
4776 }
4777
4778 if (pMedium == pToLockWrite)
4779 mediumLockList.Prepend(pMedium, true);
4780 else
4781 mediumLockList.Prepend(pMedium, fMediumLockWriteAll);
4782
4783 pMedium = pMedium->i_getParent();
4784 if (pMedium.isNull() && pToBeParent)
4785 {
4786 pMedium = pToBeParent;
4787 pToBeParent = NULL;
4788 }
4789 }
4790
4791 return mrc;
4792}
4793
4794/**
4795 * Creates a new differencing storage unit using the format of the given target
4796 * medium and the location. Note that @c aTarget must be NotCreated.
4797 *
4798 * The @a aMediumLockList parameter contains the associated medium lock list,
4799 * which must be in locked state. If @a aWait is @c true then the caller is
4800 * responsible for unlocking.
4801 *
4802 * If @a aProgress is not NULL but the object it points to is @c null then a
4803 * new progress object will be created and assigned to @a *aProgress on
4804 * success, otherwise the existing progress object is used. If @a aProgress is
4805 * NULL, then no progress object is created/used at all.
4806 *
4807 * When @a aWait is @c false, this method will create a thread to perform the
4808 * create operation asynchronously and will return immediately. Otherwise, it
4809 * will perform the operation on the calling thread and will not return to the
4810 * caller until the operation is completed. Note that @a aProgress cannot be
4811 * NULL when @a aWait is @c false (this method will assert in this case).
4812 *
4813 * @param aTarget Target medium.
4814 * @param aVariant Precise medium variant to create.
4815 * @param aMediumLockList List of media which should be locked.
4816 * @param aProgress Where to find/store a Progress object to track
4817 * operation completion.
4818 * @param aWait @c true if this method should block instead of
4819 * creating an asynchronous thread.
4820 *
4821 * @note Locks this object and @a aTarget for writing.
4822 */
4823HRESULT Medium::i_createDiffStorage(ComObjPtr<Medium> &aTarget,
4824 MediumVariant_T aVariant,
4825 MediumLockList *aMediumLockList,
4826 ComObjPtr<Progress> *aProgress,
4827 bool aWait)
4828{
4829 AssertReturn(!aTarget.isNull(), E_FAIL);
4830 AssertReturn(aMediumLockList, E_FAIL);
4831 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
4832
4833 AutoCaller autoCaller(this);
4834 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4835
4836 AutoCaller targetCaller(aTarget);
4837 if (FAILED(targetCaller.rc())) return targetCaller.rc();
4838
4839 HRESULT rc = S_OK;
4840 ComObjPtr<Progress> pProgress;
4841 Medium::Task *pTask = NULL;
4842
4843 try
4844 {
4845 AutoMultiWriteLock2 alock(this, aTarget COMMA_LOCKVAL_SRC_POS);
4846
4847 ComAssertThrow( m->type != MediumType_Writethrough
4848 && m->type != MediumType_Shareable
4849 && m->type != MediumType_Readonly, E_FAIL);
4850 ComAssertThrow(m->state == MediumState_LockedRead, E_FAIL);
4851
4852 if (aTarget->m->state != MediumState_NotCreated)
4853 throw aTarget->i_setStateError();
4854
4855 /* Check that the medium is not attached to the current state of
4856 * any VM referring to it. */
4857 for (BackRefList::const_iterator it = m->backRefs.begin();
4858 it != m->backRefs.end();
4859 ++it)
4860 {
4861 if (it->fInCurState)
4862 {
4863 /* Note: when a VM snapshot is being taken, all normal media
4864 * attached to the VM in the current state will be, as an
4865 * exception, also associated with the snapshot which is about
4866 * to create (see SnapshotMachine::init()) before deassociating
4867 * them from the current state (which takes place only on
4868 * success in Machine::fixupHardDisks()), so that the size of
4869 * snapshotIds will be 1 in this case. The extra condition is
4870 * used to filter out this legal situation. */
4871 if (it->llSnapshotIds.size() == 0)
4872 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4873 tr("Medium '%s' is attached to a virtual machine with UUID {%RTuuid}. No differencing media based on it may be created until it is detached"),
4874 m->strLocationFull.c_str(), it->machineId.raw());
4875
4876 Assert(it->llSnapshotIds.size() == 1);
4877 }
4878 }
4879
4880 if (aProgress != NULL)
4881 {
4882 /* use the existing progress object... */
4883 pProgress = *aProgress;
4884
4885 /* ...but create a new one if it is null */
4886 if (pProgress.isNull())
4887 {
4888 pProgress.createObject();
4889 rc = pProgress->init(m->pVirtualBox,
4890 static_cast<IMedium*>(this),
4891 BstrFmt(tr("Creating differencing medium storage unit '%s'"),
4892 aTarget->m->strLocationFull.c_str()).raw(),
4893 TRUE /* aCancelable */);
4894 if (FAILED(rc))
4895 throw rc;
4896 }
4897 }
4898
4899 /* setup task object to carry out the operation sync/async */
4900 pTask = new Medium::CreateDiffTask(this, pProgress, aTarget, aVariant,
4901 aMediumLockList,
4902 aWait /* fKeepMediumLockList */);
4903 rc = pTask->rc();
4904 AssertComRC(rc);
4905 if (FAILED(rc))
4906 throw rc;
4907
4908 /* register a task (it will deregister itself when done) */
4909 ++m->numCreateDiffTasks;
4910 Assert(m->numCreateDiffTasks != 0); /* overflow? */
4911
4912 aTarget->m->state = MediumState_Creating;
4913 }
4914 catch (HRESULT aRC) { rc = aRC; }
4915
4916 if (SUCCEEDED(rc))
4917 {
4918 if (aWait)
4919 {
4920 rc = pTask->runNow();
4921
4922 delete pTask;
4923 }
4924 else
4925 rc = pTask->createThread();
4926
4927 if (SUCCEEDED(rc) && aProgress != NULL)
4928 *aProgress = pProgress;
4929 }
4930 else if (pTask != NULL)
4931 delete pTask;
4932
4933 return rc;
4934}
4935
4936/**
4937 * Returns a preferred format for differencing media.
4938 */
4939Utf8Str Medium::i_getPreferredDiffFormat()
4940{
4941 AutoCaller autoCaller(this);
4942 AssertComRCReturn(autoCaller.rc(), Utf8Str::Empty);
4943
4944 /* check that our own format supports diffs */
4945 if (!(m->formatObj->i_getCapabilities() & MediumFormatCapabilities_Differencing))
4946 {
4947 /* use the default format if not */
4948 Utf8Str tmp;
4949 m->pVirtualBox->i_getDefaultHardDiskFormat(tmp);
4950 return tmp;
4951 }
4952
4953 /* m->strFormat is const, no need to lock */
4954 return m->strFormat;
4955}
4956
4957/**
4958 * Returns a preferred variant for differencing media.
4959 */
4960MediumVariant_T Medium::i_getPreferredDiffVariant()
4961{
4962 AutoCaller autoCaller(this);
4963 AssertComRCReturn(autoCaller.rc(), MediumVariant_Standard);
4964
4965 /* check that our own format supports diffs */
4966 if (!(m->formatObj->i_getCapabilities() & MediumFormatCapabilities_Differencing))
4967 return MediumVariant_Standard;
4968
4969 /* m->variant is const, no need to lock */
4970 ULONG mediumVariantFlags = (ULONG)m->variant;
4971 mediumVariantFlags &= ~(MediumVariant_Fixed | MediumVariant_VmdkStreamOptimized);
4972 mediumVariantFlags |= MediumVariant_Diff;
4973 return (MediumVariant_T)mediumVariantFlags;
4974}
4975
4976/**
4977 * Implementation for the public Medium::Close() with the exception of calling
4978 * VirtualBox::saveRegistries(), in case someone wants to call this for several
4979 * media.
4980 *
4981 * After this returns with success, uninit() has been called on the medium, and
4982 * the object is no longer usable ("not ready" state).
4983 *
4984 * @param autoCaller AutoCaller instance which must have been created on the caller's
4985 * stack for this medium. This gets released hereupon
4986 * which the Medium instance gets uninitialized.
4987 * @return
4988 */
4989HRESULT Medium::i_close(AutoCaller &autoCaller)
4990{
4991 // must temporarily drop the caller, need the tree lock first
4992 autoCaller.release();
4993
4994 // we're accessing parent/child and backrefs, so lock the tree first, then ourselves
4995 AutoMultiWriteLock2 multilock(&m->pVirtualBox->i_getMediaTreeLockHandle(),
4996 this->lockHandle()
4997 COMMA_LOCKVAL_SRC_POS);
4998
4999 autoCaller.add();
5000 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5001
5002 LogFlowFunc(("ENTER for %s\n", i_getLocationFull().c_str()));
5003
5004 bool wasCreated = true;
5005
5006 switch (m->state)
5007 {
5008 case MediumState_NotCreated:
5009 wasCreated = false;
5010 break;
5011 case MediumState_Created:
5012 case MediumState_Inaccessible:
5013 break;
5014 default:
5015 return i_setStateError();
5016 }
5017
5018 if (m->backRefs.size() != 0)
5019 return setError(VBOX_E_OBJECT_IN_USE,
5020 tr("Medium '%s' cannot be closed because it is still attached to %d virtual machines"),
5021 m->strLocationFull.c_str(), m->backRefs.size());
5022
5023 // perform extra media-dependent close checks
5024 HRESULT rc = i_canClose();
5025 if (FAILED(rc)) return rc;
5026
5027 m->fClosing = true;
5028
5029 if (wasCreated)
5030 {
5031 // remove from the list of known media before performing actual
5032 // uninitialization (to keep the media registry consistent on
5033 // failure to do so)
5034 rc = i_unregisterWithVirtualBox();
5035 if (FAILED(rc)) return rc;
5036
5037 multilock.release();
5038 // Release the AutoCaller now, as otherwise uninit() will simply hang.
5039 // Needs to be done before mark the registries as modified and saving
5040 // the registry, as otherwise there may be a deadlock with someone else
5041 // closing this object while we're in i_saveModifiedRegistries(), which
5042 // needs the media tree lock, which the other thread holds until after
5043 // uninit() below.
5044 autoCaller.release();
5045 i_markRegistriesModified();
5046 m->pVirtualBox->i_saveModifiedRegistries();
5047 }
5048 else
5049 {
5050 multilock.release();
5051 // release the AutoCaller, as otherwise uninit() will simply hang
5052 autoCaller.release();
5053 }
5054
5055 // Keep the locks held until after uninit, as otherwise the consistency
5056 // of the medium tree cannot be guaranteed.
5057 uninit();
5058
5059 LogFlowFuncLeave();
5060
5061 return rc;
5062}
5063
5064/**
5065 * Deletes the medium storage unit.
5066 *
5067 * If @a aProgress is not NULL but the object it points to is @c null then a new
5068 * progress object will be created and assigned to @a *aProgress on success,
5069 * otherwise the existing progress object is used. If Progress is NULL, then no
5070 * progress object is created/used at all.
5071 *
5072 * When @a aWait is @c false, this method will create a thread to perform the
5073 * delete operation asynchronously and will return immediately. Otherwise, it
5074 * will perform the operation on the calling thread and will not return to the
5075 * caller until the operation is completed. Note that @a aProgress cannot be
5076 * NULL when @a aWait is @c false (this method will assert in this case).
5077 *
5078 * @param aProgress Where to find/store a Progress object to track operation
5079 * completion.
5080 * @param aWait @c true if this method should block instead of creating
5081 * an asynchronous thread.
5082 *
5083 * @note Locks mVirtualBox and this object for writing. Locks medium tree for
5084 * writing.
5085 */
5086HRESULT Medium::i_deleteStorage(ComObjPtr<Progress> *aProgress,
5087 bool aWait)
5088{
5089 /** @todo r=klaus The code below needs to be double checked with regard
5090 * to lock order violations, it probably causes lock order issues related
5091 * to the AutoCaller usage. */
5092 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
5093
5094 AutoCaller autoCaller(this);
5095 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5096
5097 HRESULT rc = S_OK;
5098 ComObjPtr<Progress> pProgress;
5099 Medium::Task *pTask = NULL;
5100
5101 try
5102 {
5103 /* we're accessing the media tree, and canClose() needs it too */
5104 AutoMultiWriteLock2 multilock(&m->pVirtualBox->i_getMediaTreeLockHandle(),
5105 this->lockHandle()
5106 COMMA_LOCKVAL_SRC_POS);
5107 LogFlowThisFunc(("aWait=%RTbool locationFull=%s\n", aWait, i_getLocationFull().c_str() ));
5108
5109 if ( !(m->formatObj->i_getCapabilities() & ( MediumFormatCapabilities_CreateDynamic
5110 | MediumFormatCapabilities_CreateFixed)))
5111 throw setError(VBOX_E_NOT_SUPPORTED,
5112 tr("Medium format '%s' does not support storage deletion"),
5113 m->strFormat.c_str());
5114
5115 /* Wait for a concurrently running Medium::i_queryInfo to complete. */
5116 /** @todo r=klaus would be great if this could be moved to the async
5117 * part of the operation as it can take quite a while */
5118 if (m->queryInfoRunning)
5119 {
5120 while (m->queryInfoRunning)
5121 {
5122 multilock.release();
5123 /* Must not hold the media tree lock or the object lock, as
5124 * Medium::i_queryInfo needs this lock and thus we would run
5125 * into a deadlock here. */
5126 Assert(!m->pVirtualBox->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5127 Assert(!isWriteLockOnCurrentThread());
5128 {
5129 AutoReadLock qlock(m->queryInfoSem COMMA_LOCKVAL_SRC_POS);
5130 }
5131 multilock.acquire();
5132 }
5133 }
5134
5135 /* Note that we are fine with Inaccessible state too: a) for symmetry
5136 * with create calls and b) because it doesn't really harm to try, if
5137 * it is really inaccessible, the delete operation will fail anyway.
5138 * Accepting Inaccessible state is especially important because all
5139 * registered media are initially Inaccessible upon VBoxSVC startup
5140 * until COMGETTER(RefreshState) is called. Accept Deleting state
5141 * because some callers need to put the medium in this state early
5142 * to prevent races. */
5143 switch (m->state)
5144 {
5145 case MediumState_Created:
5146 case MediumState_Deleting:
5147 case MediumState_Inaccessible:
5148 break;
5149 default:
5150 throw i_setStateError();
5151 }
5152
5153 if (m->backRefs.size() != 0)
5154 {
5155 Utf8Str strMachines;
5156 for (BackRefList::const_iterator it = m->backRefs.begin();
5157 it != m->backRefs.end();
5158 ++it)
5159 {
5160 const BackRef &b = *it;
5161 if (strMachines.length())
5162 strMachines.append(", ");
5163 strMachines.append(b.machineId.toString().c_str());
5164 }
5165#ifdef DEBUG
5166 i_dumpBackRefs();
5167#endif
5168 throw setError(VBOX_E_OBJECT_IN_USE,
5169 tr("Cannot delete storage: medium '%s' is still attached to the following %d virtual machine(s): %s"),
5170 m->strLocationFull.c_str(),
5171 m->backRefs.size(),
5172 strMachines.c_str());
5173 }
5174
5175 rc = i_canClose();
5176 if (FAILED(rc))
5177 throw rc;
5178
5179 /* go to Deleting state, so that the medium is not actually locked */
5180 if (m->state != MediumState_Deleting)
5181 {
5182 rc = i_markForDeletion();
5183 if (FAILED(rc))
5184 throw rc;
5185 }
5186
5187 /* Build the medium lock list. */
5188 MediumLockList *pMediumLockList(new MediumLockList());
5189 multilock.release();
5190 rc = i_createMediumLockList(true /* fFailIfInaccessible */,
5191 this /* pToLockWrite */,
5192 false /* fMediumLockWriteAll */,
5193 NULL,
5194 *pMediumLockList);
5195 multilock.acquire();
5196 if (FAILED(rc))
5197 {
5198 delete pMediumLockList;
5199 throw rc;
5200 }
5201
5202 multilock.release();
5203 rc = pMediumLockList->Lock();
5204 multilock.acquire();
5205 if (FAILED(rc))
5206 {
5207 delete pMediumLockList;
5208 throw setError(rc,
5209 tr("Failed to lock media when deleting '%s'"),
5210 i_getLocationFull().c_str());
5211 }
5212
5213 /* try to remove from the list of known media before performing
5214 * actual deletion (we favor the consistency of the media registry
5215 * which would have been broken if unregisterWithVirtualBox() failed
5216 * after we successfully deleted the storage) */
5217 rc = i_unregisterWithVirtualBox();
5218 if (FAILED(rc))
5219 throw rc;
5220 // no longer need lock
5221 multilock.release();
5222 i_markRegistriesModified();
5223
5224 if (aProgress != NULL)
5225 {
5226 /* use the existing progress object... */
5227 pProgress = *aProgress;
5228
5229 /* ...but create a new one if it is null */
5230 if (pProgress.isNull())
5231 {
5232 pProgress.createObject();
5233 rc = pProgress->init(m->pVirtualBox,
5234 static_cast<IMedium*>(this),
5235 BstrFmt(tr("Deleting medium storage unit '%s'"), m->strLocationFull.c_str()).raw(),
5236 FALSE /* aCancelable */);
5237 if (FAILED(rc))
5238 throw rc;
5239 }
5240 }
5241
5242 /* setup task object to carry out the operation sync/async */
5243 pTask = new Medium::DeleteTask(this, pProgress, pMediumLockList);
5244 rc = pTask->rc();
5245 AssertComRC(rc);
5246 if (FAILED(rc))
5247 throw rc;
5248 }
5249 catch (HRESULT aRC) { rc = aRC; }
5250
5251 if (SUCCEEDED(rc))
5252 {
5253 if (aWait)
5254 {
5255 rc = pTask->runNow();
5256
5257 delete pTask;
5258 }
5259 else
5260 rc = pTask->createThread();
5261
5262 if (SUCCEEDED(rc) && aProgress != NULL)
5263 *aProgress = pProgress;
5264
5265 }
5266 else
5267 {
5268 if (pTask)
5269 delete pTask;
5270
5271 /* Undo deleting state if necessary. */
5272 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5273 /* Make sure that any error signalled by unmarkForDeletion() is not
5274 * ending up in the error list (if the caller uses MultiResult). It
5275 * usually is spurious, as in most cases the medium hasn't been marked
5276 * for deletion when the error was thrown above. */
5277 ErrorInfoKeeper eik;
5278 i_unmarkForDeletion();
5279 }
5280
5281 return rc;
5282}
5283
5284/**
5285 * Mark a medium for deletion.
5286 *
5287 * @note Caller must hold the write lock on this medium!
5288 */
5289HRESULT Medium::i_markForDeletion()
5290{
5291 ComAssertRet(isWriteLockOnCurrentThread(), E_FAIL);
5292 switch (m->state)
5293 {
5294 case MediumState_Created:
5295 case MediumState_Inaccessible:
5296 m->preLockState = m->state;
5297 m->state = MediumState_Deleting;
5298 return S_OK;
5299 default:
5300 return i_setStateError();
5301 }
5302}
5303
5304/**
5305 * Removes the "mark for deletion".
5306 *
5307 * @note Caller must hold the write lock on this medium!
5308 */
5309HRESULT Medium::i_unmarkForDeletion()
5310{
5311 ComAssertRet(isWriteLockOnCurrentThread(), E_FAIL);
5312 switch (m->state)
5313 {
5314 case MediumState_Deleting:
5315 m->state = m->preLockState;
5316 return S_OK;
5317 default:
5318 return i_setStateError();
5319 }
5320}
5321
5322/**
5323 * Mark a medium for deletion which is in locked state.
5324 *
5325 * @note Caller must hold the write lock on this medium!
5326 */
5327HRESULT Medium::i_markLockedForDeletion()
5328{
5329 ComAssertRet(isWriteLockOnCurrentThread(), E_FAIL);
5330 if ( ( m->state == MediumState_LockedRead
5331 || m->state == MediumState_LockedWrite)
5332 && m->preLockState == MediumState_Created)
5333 {
5334 m->preLockState = MediumState_Deleting;
5335 return S_OK;
5336 }
5337 else
5338 return i_setStateError();
5339}
5340
5341/**
5342 * Removes the "mark for deletion" for a medium in locked state.
5343 *
5344 * @note Caller must hold the write lock on this medium!
5345 */
5346HRESULT Medium::i_unmarkLockedForDeletion()
5347{
5348 ComAssertRet(isWriteLockOnCurrentThread(), E_FAIL);
5349 if ( ( m->state == MediumState_LockedRead
5350 || m->state == MediumState_LockedWrite)
5351 && m->preLockState == MediumState_Deleting)
5352 {
5353 m->preLockState = MediumState_Created;
5354 return S_OK;
5355 }
5356 else
5357 return i_setStateError();
5358}
5359
5360/**
5361 * Queries the preferred merge direction from this to the other medium, i.e.
5362 * the one which requires the least amount of I/O and therefore time and
5363 * disk consumption.
5364 *
5365 * @returns Status code.
5366 * @retval E_FAIL in case determining the merge direction fails for some reason,
5367 * for example if getting the size of the media fails. There is no
5368 * error set though and the caller is free to continue to find out
5369 * what was going wrong later. Leaves fMergeForward unset.
5370 * @retval VBOX_E_INVALID_OBJECT_STATE if both media are not related to each other
5371 * An error is set.
5372 * @param pOther The other medium to merge with.
5373 * @param fMergeForward Resulting preferred merge direction (out).
5374 */
5375HRESULT Medium::i_queryPreferredMergeDirection(const ComObjPtr<Medium> &pOther,
5376 bool &fMergeForward)
5377{
5378 /** @todo r=klaus The code below needs to be double checked with regard
5379 * to lock order violations, it probably causes lock order issues related
5380 * to the AutoCaller usage. Likewise the code using this method seems
5381 * problematic. */
5382 AssertReturn(pOther != NULL, E_FAIL);
5383 AssertReturn(pOther != this, E_FAIL);
5384
5385 AutoCaller autoCaller(this);
5386 AssertComRCReturnRC(autoCaller.rc());
5387
5388 AutoCaller otherCaller(pOther);
5389 AssertComRCReturnRC(otherCaller.rc());
5390
5391 HRESULT rc = S_OK;
5392 bool fThisParent = false; /**<< Flag whether this medium is the parent of pOther. */
5393
5394 try
5395 {
5396 // locking: we need the tree lock first because we access parent pointers
5397 AutoWriteLock treeLock(m->pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5398
5399 /* more sanity checking and figuring out the current merge direction */
5400 ComObjPtr<Medium> pMedium = i_getParent();
5401 while (!pMedium.isNull() && pMedium != pOther)
5402 pMedium = pMedium->i_getParent();
5403 if (pMedium == pOther)
5404 fThisParent = false;
5405 else
5406 {
5407 pMedium = pOther->i_getParent();
5408 while (!pMedium.isNull() && pMedium != this)
5409 pMedium = pMedium->i_getParent();
5410 if (pMedium == this)
5411 fThisParent = true;
5412 else
5413 {
5414 Utf8Str tgtLoc;
5415 {
5416 AutoReadLock alock(pOther COMMA_LOCKVAL_SRC_POS);
5417 tgtLoc = pOther->i_getLocationFull();
5418 }
5419
5420 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5421 throw setError(VBOX_E_INVALID_OBJECT_STATE,
5422 tr("Media '%s' and '%s' are unrelated"),
5423 m->strLocationFull.c_str(), tgtLoc.c_str());
5424 }
5425 }
5426
5427 /*
5428 * Figure out the preferred merge direction. The current way is to
5429 * get the current sizes of file based images and select the merge
5430 * direction depending on the size.
5431 *
5432 * Can't use the VD API to get current size here as the media might
5433 * be write locked by a running VM. Resort to RTFileQuerySize().
5434 */
5435 int vrc = VINF_SUCCESS;
5436 uint64_t cbMediumThis = 0;
5437 uint64_t cbMediumOther = 0;
5438
5439 if (i_isMediumFormatFile() && pOther->i_isMediumFormatFile())
5440 {
5441 vrc = RTFileQuerySize(this->i_getLocationFull().c_str(), &cbMediumThis);
5442 if (RT_SUCCESS(vrc))
5443 {
5444 vrc = RTFileQuerySize(pOther->i_getLocationFull().c_str(),
5445 &cbMediumOther);
5446 }
5447
5448 if (RT_FAILURE(vrc))
5449 rc = E_FAIL;
5450 else
5451 {
5452 /*
5453 * Check which merge direction might be more optimal.
5454 * This method is not bullet proof of course as there might
5455 * be overlapping blocks in the images so the file size is
5456 * not the best indicator but it is good enough for our purpose
5457 * and everything else is too complicated, especially when the
5458 * media are used by a running VM.
5459 */
5460 bool fMergeIntoThis = cbMediumThis > cbMediumOther;
5461 fMergeForward = fMergeIntoThis != fThisParent;
5462 }
5463 }
5464 }
5465 catch (HRESULT aRC) { rc = aRC; }
5466
5467 return rc;
5468}
5469
5470/**
5471 * Prepares this (source) medium, target medium and all intermediate media
5472 * for the merge operation.
5473 *
5474 * This method is to be called prior to calling the #mergeTo() to perform
5475 * necessary consistency checks and place involved media to appropriate
5476 * states. If #mergeTo() is not called or fails, the state modifications
5477 * performed by this method must be undone by #i_cancelMergeTo().
5478 *
5479 * See #mergeTo() for more information about merging.
5480 *
5481 * @param pTarget Target medium.
5482 * @param aMachineId Allowed machine attachment. NULL means do not check.
5483 * @param aSnapshotId Allowed snapshot attachment. NULL or empty UUID means
5484 * do not check.
5485 * @param fLockMedia Flag whether to lock the medium lock list or not.
5486 * If set to false and the medium lock list locking fails
5487 * later you must call #i_cancelMergeTo().
5488 * @param fMergeForward Resulting merge direction (out).
5489 * @param pParentForTarget New parent for target medium after merge (out).
5490 * @param aChildrenToReparent Medium lock list containing all children of the
5491 * source which will have to be reparented to the target
5492 * after merge (out).
5493 * @param aMediumLockList Medium locking information (out).
5494 *
5495 * @note Locks medium tree for reading. Locks this object, aTarget and all
5496 * intermediate media for writing.
5497 */
5498HRESULT Medium::i_prepareMergeTo(const ComObjPtr<Medium> &pTarget,
5499 const Guid *aMachineId,
5500 const Guid *aSnapshotId,
5501 bool fLockMedia,
5502 bool &fMergeForward,
5503 ComObjPtr<Medium> &pParentForTarget,
5504 MediumLockList * &aChildrenToReparent,
5505 MediumLockList * &aMediumLockList)
5506{
5507 /** @todo r=klaus The code below needs to be double checked with regard
5508 * to lock order violations, it probably causes lock order issues related
5509 * to the AutoCaller usage. Likewise the code using this method seems
5510 * problematic. */
5511 AssertReturn(pTarget != NULL, E_FAIL);
5512 AssertReturn(pTarget != this, E_FAIL);
5513
5514 AutoCaller autoCaller(this);
5515 AssertComRCReturnRC(autoCaller.rc());
5516
5517 AutoCaller targetCaller(pTarget);
5518 AssertComRCReturnRC(targetCaller.rc());
5519
5520 HRESULT rc = S_OK;
5521 fMergeForward = false;
5522 pParentForTarget.setNull();
5523 Assert(aChildrenToReparent == NULL);
5524 aChildrenToReparent = NULL;
5525 Assert(aMediumLockList == NULL);
5526 aMediumLockList = NULL;
5527
5528 try
5529 {
5530 // locking: we need the tree lock first because we access parent pointers
5531 AutoWriteLock treeLock(m->pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5532
5533 /* more sanity checking and figuring out the merge direction */
5534 ComObjPtr<Medium> pMedium = i_getParent();
5535 while (!pMedium.isNull() && pMedium != pTarget)
5536 pMedium = pMedium->i_getParent();
5537 if (pMedium == pTarget)
5538 fMergeForward = false;
5539 else
5540 {
5541 pMedium = pTarget->i_getParent();
5542 while (!pMedium.isNull() && pMedium != this)
5543 pMedium = pMedium->i_getParent();
5544 if (pMedium == this)
5545 fMergeForward = true;
5546 else
5547 {
5548 Utf8Str tgtLoc;
5549 {
5550 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
5551 tgtLoc = pTarget->i_getLocationFull();
5552 }
5553
5554 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5555 throw setError(VBOX_E_INVALID_OBJECT_STATE,
5556 tr("Media '%s' and '%s' are unrelated"),
5557 m->strLocationFull.c_str(), tgtLoc.c_str());
5558 }
5559 }
5560
5561 /* Build the lock list. */
5562 aMediumLockList = new MediumLockList();
5563 treeLock.release();
5564 if (fMergeForward)
5565 rc = pTarget->i_createMediumLockList(true /* fFailIfInaccessible */,
5566 pTarget /* pToLockWrite */,
5567 false /* fMediumLockWriteAll */,
5568 NULL,
5569 *aMediumLockList);
5570 else
5571 rc = i_createMediumLockList(true /* fFailIfInaccessible */,
5572 pTarget /* pToLockWrite */,
5573 false /* fMediumLockWriteAll */,
5574 NULL,
5575 *aMediumLockList);
5576 treeLock.acquire();
5577 if (FAILED(rc))
5578 throw rc;
5579
5580 /* Sanity checking, must be after lock list creation as it depends on
5581 * valid medium states. The medium objects must be accessible. Only
5582 * do this if immediate locking is requested, otherwise it fails when
5583 * we construct a medium lock list for an already running VM. Snapshot
5584 * deletion uses this to simplify its life. */
5585 if (fLockMedia)
5586 {
5587 {
5588 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5589 if (m->state != MediumState_Created)
5590 throw i_setStateError();
5591 }
5592 {
5593 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
5594 if (pTarget->m->state != MediumState_Created)
5595 throw pTarget->i_setStateError();
5596 }
5597 }
5598
5599 /* check medium attachment and other sanity conditions */
5600 if (fMergeForward)
5601 {
5602 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5603 if (i_getChildren().size() > 1)
5604 {
5605 throw setError(VBOX_E_INVALID_OBJECT_STATE,
5606 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
5607 m->strLocationFull.c_str(), i_getChildren().size());
5608 }
5609 /* One backreference is only allowed if the machine ID is not empty
5610 * and it matches the machine the medium is attached to (including
5611 * the snapshot ID if not empty). */
5612 if ( m->backRefs.size() != 0
5613 && ( !aMachineId
5614 || m->backRefs.size() != 1
5615 || aMachineId->isZero()
5616 || *i_getFirstMachineBackrefId() != *aMachineId
5617 || ( (!aSnapshotId || !aSnapshotId->isZero())
5618 && *i_getFirstMachineBackrefSnapshotId() != *aSnapshotId)))
5619 throw setError(VBOX_E_OBJECT_IN_USE,
5620 tr("Medium '%s' is attached to %d virtual machines"),
5621 m->strLocationFull.c_str(), m->backRefs.size());
5622 if (m->type == MediumType_Immutable)
5623 throw setError(VBOX_E_INVALID_OBJECT_STATE,
5624 tr("Medium '%s' is immutable"),
5625 m->strLocationFull.c_str());
5626 if (m->type == MediumType_MultiAttach)
5627 throw setError(VBOX_E_INVALID_OBJECT_STATE,
5628 tr("Medium '%s' is multi-attach"),
5629 m->strLocationFull.c_str());
5630 }
5631 else
5632 {
5633 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
5634 if (pTarget->i_getChildren().size() > 1)
5635 {
5636 throw setError(VBOX_E_OBJECT_IN_USE,
5637 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
5638 pTarget->m->strLocationFull.c_str(),
5639 pTarget->i_getChildren().size());
5640 }
5641 if (pTarget->m->type == MediumType_Immutable)
5642 throw setError(VBOX_E_INVALID_OBJECT_STATE,
5643 tr("Medium '%s' is immutable"),
5644 pTarget->m->strLocationFull.c_str());
5645 if (pTarget->m->type == MediumType_MultiAttach)
5646 throw setError(VBOX_E_INVALID_OBJECT_STATE,
5647 tr("Medium '%s' is multi-attach"),
5648 pTarget->m->strLocationFull.c_str());
5649 }
5650 ComObjPtr<Medium> pLast(fMergeForward ? (Medium *)pTarget : this);
5651 ComObjPtr<Medium> pLastIntermediate = pLast->i_getParent();
5652 for (pLast = pLastIntermediate;
5653 !pLast.isNull() && pLast != pTarget && pLast != this;
5654 pLast = pLast->i_getParent())
5655 {
5656 AutoReadLock alock(pLast COMMA_LOCKVAL_SRC_POS);
5657 if (pLast->i_getChildren().size() > 1)
5658 {
5659 throw setError(VBOX_E_OBJECT_IN_USE,
5660 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
5661 pLast->m->strLocationFull.c_str(),
5662 pLast->i_getChildren().size());
5663 }
5664 if (pLast->m->backRefs.size() != 0)
5665 throw setError(VBOX_E_OBJECT_IN_USE,
5666 tr("Medium '%s' is attached to %d virtual machines"),
5667 pLast->m->strLocationFull.c_str(),
5668 pLast->m->backRefs.size());
5669
5670 }
5671
5672 /* Update medium states appropriately */
5673 {
5674 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5675
5676 if (m->state == MediumState_Created)
5677 {
5678 rc = i_markForDeletion();
5679 if (FAILED(rc))
5680 throw rc;
5681 }
5682 else
5683 {
5684 if (fLockMedia)
5685 throw i_setStateError();
5686 else if ( m->state == MediumState_LockedWrite
5687 || m->state == MediumState_LockedRead)
5688 {
5689 /* Either mark it for deletion in locked state or allow
5690 * others to have done so. */
5691 if (m->preLockState == MediumState_Created)
5692 i_markLockedForDeletion();
5693 else if (m->preLockState != MediumState_Deleting)
5694 throw i_setStateError();
5695 }
5696 else
5697 throw i_setStateError();
5698 }
5699 }
5700
5701 if (fMergeForward)
5702 {
5703 /* we will need parent to reparent target */
5704 pParentForTarget = i_getParent();
5705 }
5706 else
5707 {
5708 /* we will need to reparent children of the source */
5709 aChildrenToReparent = new MediumLockList();
5710 for (MediaList::const_iterator it = i_getChildren().begin();
5711 it != i_getChildren().end();
5712 ++it)
5713 {
5714 pMedium = *it;
5715 aChildrenToReparent->Append(pMedium, true /* fLockWrite */);
5716 }
5717 if (fLockMedia && aChildrenToReparent)
5718 {
5719 treeLock.release();
5720 rc = aChildrenToReparent->Lock();
5721 treeLock.acquire();
5722 if (FAILED(rc))
5723 throw rc;
5724 }
5725 }
5726 for (pLast = pLastIntermediate;
5727 !pLast.isNull() && pLast != pTarget && pLast != this;
5728 pLast = pLast->i_getParent())
5729 {
5730 AutoWriteLock alock(pLast COMMA_LOCKVAL_SRC_POS);
5731 if (pLast->m->state == MediumState_Created)
5732 {
5733 rc = pLast->i_markForDeletion();
5734 if (FAILED(rc))
5735 throw rc;
5736 }
5737 else
5738 throw pLast->i_setStateError();
5739 }
5740
5741 /* Tweak the lock list in the backward merge case, as the target
5742 * isn't marked to be locked for writing yet. */
5743 if (!fMergeForward)
5744 {
5745 MediumLockList::Base::iterator lockListBegin =
5746 aMediumLockList->GetBegin();
5747 MediumLockList::Base::iterator lockListEnd =
5748 aMediumLockList->GetEnd();
5749 ++lockListEnd;
5750 for (MediumLockList::Base::iterator it = lockListBegin;
5751 it != lockListEnd;
5752 ++it)
5753 {
5754 MediumLock &mediumLock = *it;
5755 if (mediumLock.GetMedium() == pTarget)
5756 {
5757 HRESULT rc2 = mediumLock.UpdateLock(true);
5758 AssertComRC(rc2);
5759 break;
5760 }
5761 }
5762 }
5763
5764 if (fLockMedia)
5765 {
5766 treeLock.release();
5767 rc = aMediumLockList->Lock();
5768 treeLock.acquire();
5769 if (FAILED(rc))
5770 {
5771 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
5772 throw setError(rc,
5773 tr("Failed to lock media when merging to '%s'"),
5774 pTarget->i_getLocationFull().c_str());
5775 }
5776 }
5777 }
5778 catch (HRESULT aRC) { rc = aRC; }
5779
5780 if (FAILED(rc))
5781 {
5782 if (aMediumLockList)
5783 {
5784 delete aMediumLockList;
5785 aMediumLockList = NULL;
5786 }
5787 if (aChildrenToReparent)
5788 {
5789 delete aChildrenToReparent;
5790 aChildrenToReparent = NULL;
5791 }
5792 }
5793
5794 return rc;
5795}
5796
5797/**
5798 * Merges this medium to the specified medium which must be either its
5799 * direct ancestor or descendant.
5800 *
5801 * Given this medium is SOURCE and the specified medium is TARGET, we will
5802 * get two variants of the merge operation:
5803 *
5804 * forward merge
5805 * ------------------------->
5806 * [Extra] <- SOURCE <- Intermediate <- TARGET
5807 * Any Del Del LockWr
5808 *
5809 *
5810 * backward merge
5811 * <-------------------------
5812 * TARGET <- Intermediate <- SOURCE <- [Extra]
5813 * LockWr Del Del LockWr
5814 *
5815 * Each diagram shows the involved media on the media chain where
5816 * SOURCE and TARGET belong. Under each medium there is a state value which
5817 * the medium must have at a time of the mergeTo() call.
5818 *
5819 * The media in the square braces may be absent (e.g. when the forward
5820 * operation takes place and SOURCE is the base medium, or when the backward
5821 * merge operation takes place and TARGET is the last child in the chain) but if
5822 * they present they are involved too as shown.
5823 *
5824 * Neither the source medium nor intermediate media may be attached to
5825 * any VM directly or in the snapshot, otherwise this method will assert.
5826 *
5827 * The #i_prepareMergeTo() method must be called prior to this method to place
5828 * all involved to necessary states and perform other consistency checks.
5829 *
5830 * If @a aWait is @c true then this method will perform the operation on the
5831 * calling thread and will not return to the caller until the operation is
5832 * completed. When this method succeeds, all intermediate medium objects in
5833 * the chain will be uninitialized, the state of the target medium (and all
5834 * involved extra media) will be restored. @a aMediumLockList will not be
5835 * deleted, whether the operation is successful or not. The caller has to do
5836 * this if appropriate. Note that this (source) medium is not uninitialized
5837 * because of possible AutoCaller instances held by the caller of this method
5838 * on the current thread. It's therefore the responsibility of the caller to
5839 * call Medium::uninit() after releasing all callers.
5840 *
5841 * If @a aWait is @c false then this method will create a thread to perform the
5842 * operation asynchronously and will return immediately. If the operation
5843 * succeeds, the thread will uninitialize the source medium object and all
5844 * intermediate medium objects in the chain, reset the state of the target
5845 * medium (and all involved extra media) and delete @a aMediumLockList.
5846 * If the operation fails, the thread will only reset the states of all
5847 * involved media and delete @a aMediumLockList.
5848 *
5849 * When this method fails (regardless of the @a aWait mode), it is a caller's
5850 * responsibility to undo state changes and delete @a aMediumLockList using
5851 * #i_cancelMergeTo().
5852 *
5853 * If @a aProgress is not NULL but the object it points to is @c null then a new
5854 * progress object will be created and assigned to @a *aProgress on success,
5855 * otherwise the existing progress object is used. If Progress is NULL, then no
5856 * progress object is created/used at all. Note that @a aProgress cannot be
5857 * NULL when @a aWait is @c false (this method will assert in this case).
5858 *
5859 * @param pTarget Target medium.
5860 * @param fMergeForward Merge direction.
5861 * @param pParentForTarget New parent for target medium after merge.
5862 * @param aChildrenToReparent List of children of the source which will have
5863 * to be reparented to the target after merge.
5864 * @param aMediumLockList Medium locking information.
5865 * @param aProgress Where to find/store a Progress object to track operation
5866 * completion.
5867 * @param aWait @c true if this method should block instead of creating
5868 * an asynchronous thread.
5869 *
5870 * @note Locks the tree lock for writing. Locks the media from the chain
5871 * for writing.
5872 */
5873HRESULT Medium::i_mergeTo(const ComObjPtr<Medium> &pTarget,
5874 bool fMergeForward,
5875 const ComObjPtr<Medium> &pParentForTarget,
5876 MediumLockList *aChildrenToReparent,
5877 MediumLockList *aMediumLockList,
5878 ComObjPtr<Progress> *aProgress,
5879 bool aWait)
5880{
5881 AssertReturn(pTarget != NULL, E_FAIL);
5882 AssertReturn(pTarget != this, E_FAIL);
5883 AssertReturn(aMediumLockList != NULL, E_FAIL);
5884 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
5885
5886 AutoCaller autoCaller(this);
5887 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5888
5889 AutoCaller targetCaller(pTarget);
5890 AssertComRCReturnRC(targetCaller.rc());
5891
5892 HRESULT rc = S_OK;
5893 ComObjPtr<Progress> pProgress;
5894 Medium::Task *pTask = NULL;
5895
5896 try
5897 {
5898 if (aProgress != NULL)
5899 {
5900 /* use the existing progress object... */
5901 pProgress = *aProgress;
5902
5903 /* ...but create a new one if it is null */
5904 if (pProgress.isNull())
5905 {
5906 Utf8Str tgtName;
5907 {
5908 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
5909 tgtName = pTarget->i_getName();
5910 }
5911
5912 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5913
5914 pProgress.createObject();
5915 rc = pProgress->init(m->pVirtualBox,
5916 static_cast<IMedium*>(this),
5917 BstrFmt(tr("Merging medium '%s' to '%s'"),
5918 i_getName().c_str(),
5919 tgtName.c_str()).raw(),
5920 TRUE /* aCancelable */);
5921 if (FAILED(rc))
5922 throw rc;
5923 }
5924 }
5925
5926 /* setup task object to carry out the operation sync/async */
5927 pTask = new Medium::MergeTask(this, pTarget, fMergeForward,
5928 pParentForTarget, aChildrenToReparent,
5929 pProgress, aMediumLockList,
5930 aWait /* fKeepMediumLockList */);
5931 rc = pTask->rc();
5932 AssertComRC(rc);
5933 if (FAILED(rc))
5934 throw rc;
5935 }
5936 catch (HRESULT aRC) { rc = aRC; }
5937
5938 if (SUCCEEDED(rc))
5939 {
5940 if (aWait)
5941 {
5942 rc = pTask->runNow();
5943
5944 delete pTask;
5945 }
5946 else
5947 rc = pTask->createThread();
5948
5949 if (SUCCEEDED(rc) && aProgress != NULL)
5950 *aProgress = pProgress;
5951 }
5952 else if (pTask != NULL)
5953 delete pTask;
5954
5955 return rc;
5956}
5957
5958/**
5959 * Undoes what #i_prepareMergeTo() did. Must be called if #mergeTo() is not
5960 * called or fails. Frees memory occupied by @a aMediumLockList and unlocks
5961 * the medium objects in @a aChildrenToReparent.
5962 *
5963 * @param aChildrenToReparent List of children of the source which will have
5964 * to be reparented to the target after merge.
5965 * @param aMediumLockList Medium locking information.
5966 *
5967 * @note Locks the media from the chain for writing.
5968 */
5969void Medium::i_cancelMergeTo(MediumLockList *aChildrenToReparent,
5970 MediumLockList *aMediumLockList)
5971{
5972 AutoCaller autoCaller(this);
5973 AssertComRCReturnVoid(autoCaller.rc());
5974
5975 AssertReturnVoid(aMediumLockList != NULL);
5976
5977 /* Revert media marked for deletion to previous state. */
5978 HRESULT rc;
5979 MediumLockList::Base::const_iterator mediumListBegin =
5980 aMediumLockList->GetBegin();
5981 MediumLockList::Base::const_iterator mediumListEnd =
5982 aMediumLockList->GetEnd();
5983 for (MediumLockList::Base::const_iterator it = mediumListBegin;
5984 it != mediumListEnd;
5985 ++it)
5986 {
5987 const MediumLock &mediumLock = *it;
5988 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
5989 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
5990
5991 if (pMedium->m->state == MediumState_Deleting)
5992 {
5993 rc = pMedium->i_unmarkForDeletion();
5994 AssertComRC(rc);
5995 }
5996 else if ( ( pMedium->m->state == MediumState_LockedWrite
5997 || pMedium->m->state == MediumState_LockedRead)
5998 && pMedium->m->preLockState == MediumState_Deleting)
5999 {
6000 rc = pMedium->i_unmarkLockedForDeletion();
6001 AssertComRC(rc);
6002 }
6003 }
6004
6005 /* the destructor will do the work */
6006 delete aMediumLockList;
6007
6008 /* unlock the children which had to be reparented, the destructor will do
6009 * the work */
6010 if (aChildrenToReparent)
6011 delete aChildrenToReparent;
6012}
6013
6014/**
6015 * Fix the parent UUID of all children to point to this medium as their
6016 * parent.
6017 */
6018HRESULT Medium::i_fixParentUuidOfChildren(MediumLockList *pChildrenToReparent)
6019{
6020 /** @todo r=klaus The code below needs to be double checked with regard
6021 * to lock order violations, it probably causes lock order issues related
6022 * to the AutoCaller usage. Likewise the code using this method seems
6023 * problematic. */
6024 Assert(!isWriteLockOnCurrentThread());
6025 Assert(!m->pVirtualBox->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
6026 MediumLockList mediumLockList;
6027 HRESULT rc = i_createMediumLockList(true /* fFailIfInaccessible */,
6028 NULL /* pToLockWrite */,
6029 false /* fMediumLockWriteAll */,
6030 this,
6031 mediumLockList);
6032 AssertComRCReturnRC(rc);
6033
6034 try
6035 {
6036 PVDISK hdd;
6037 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
6038 ComAssertRCThrow(vrc, E_FAIL);
6039
6040 try
6041 {
6042 MediumLockList::Base::iterator lockListBegin =
6043 mediumLockList.GetBegin();
6044 MediumLockList::Base::iterator lockListEnd =
6045 mediumLockList.GetEnd();
6046 for (MediumLockList::Base::iterator it = lockListBegin;
6047 it != lockListEnd;
6048 ++it)
6049 {
6050 MediumLock &mediumLock = *it;
6051 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6052 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6053
6054 // open the medium
6055 vrc = VDOpen(hdd,
6056 pMedium->m->strFormat.c_str(),
6057 pMedium->m->strLocationFull.c_str(),
6058 VD_OPEN_FLAGS_READONLY | m->uOpenFlagsDef,
6059 pMedium->m->vdImageIfaces);
6060 if (RT_FAILURE(vrc))
6061 throw vrc;
6062 }
6063
6064 MediumLockList::Base::iterator childrenBegin = pChildrenToReparent->GetBegin();
6065 MediumLockList::Base::iterator childrenEnd = pChildrenToReparent->GetEnd();
6066 for (MediumLockList::Base::iterator it = childrenBegin;
6067 it != childrenEnd;
6068 ++it)
6069 {
6070 Medium *pMedium = it->GetMedium();
6071 /* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
6072 vrc = VDOpen(hdd,
6073 pMedium->m->strFormat.c_str(),
6074 pMedium->m->strLocationFull.c_str(),
6075 VD_OPEN_FLAGS_INFO | m->uOpenFlagsDef,
6076 pMedium->m->vdImageIfaces);
6077 if (RT_FAILURE(vrc))
6078 throw vrc;
6079
6080 vrc = VDSetParentUuid(hdd, VD_LAST_IMAGE, m->id.raw());
6081 if (RT_FAILURE(vrc))
6082 throw vrc;
6083
6084 vrc = VDClose(hdd, false /* fDelete */);
6085 if (RT_FAILURE(vrc))
6086 throw vrc;
6087 }
6088 }
6089 catch (HRESULT aRC) { rc = aRC; }
6090 catch (int aVRC)
6091 {
6092 rc = setError(E_FAIL,
6093 tr("Could not update medium UUID references to parent '%s' (%s)"),
6094 m->strLocationFull.c_str(),
6095 i_vdError(aVRC).c_str());
6096 }
6097
6098 VDDestroy(hdd);
6099 }
6100 catch (HRESULT aRC) { rc = aRC; }
6101
6102 return rc;
6103}
6104
6105/**
6106 *
6107 * @note Similar code exists in i_taskExportHandler.
6108 */
6109HRESULT Medium::i_addRawToFss(const char *aFilename, SecretKeyStore *pKeyStore, RTVFSFSSTREAM hVfsFssDst,
6110 const ComObjPtr<Progress> &aProgress, bool fSparse)
6111{
6112 /** @todo fix progress object. */
6113
6114 /*
6115 * Build the source lock list and lock the images.
6116 */
6117 MediumLockList SourceMediumLockList;
6118 HRESULT rc = i_createMediumLockList(true /* fFailIfInaccessible */,
6119 NULL /* pToLockWrite */,
6120 false /* fMediumLockWriteAll */,
6121 NULL,
6122 SourceMediumLockList);
6123 if (SUCCEEDED(rc))
6124 rc = SourceMediumLockList.Lock();
6125 if (FAILED(rc))
6126 return rc;
6127
6128 try
6129 {
6130 /*
6131 * Lock all in {parent,child} order.
6132 */
6133 ComObjPtr<Medium> pBase = i_getBase();
6134 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6135
6136 PVDISK hdd;
6137 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
6138 ComAssertRCThrow(vrc, E_FAIL);
6139
6140 try
6141 {
6142 settings::StringsMap::iterator itKeyStore = pBase->m->mapProperties.find("CRYPT/KeyStore");
6143 if (itKeyStore != pBase->m->mapProperties.end())
6144 {
6145 settings::StringsMap::iterator itKeyId = pBase->m->mapProperties.find("CRYPT/KeyId");
6146
6147#ifdef VBOX_WITH_EXTPACK
6148 ExtPackManager *pExtPackManager = m->pVirtualBox->i_getExtPackManager();
6149 if (pExtPackManager->i_isExtPackUsable(ORACLE_PUEL_EXTPACK_NAME))
6150 {
6151 /* Load the plugin */
6152 Utf8Str strPlugin;
6153 rc = pExtPackManager->i_getLibraryPathForExtPack(g_szVDPlugin, ORACLE_PUEL_EXTPACK_NAME, &strPlugin);
6154 if (SUCCEEDED(rc))
6155 {
6156 vrc = VDPluginLoadFromFilename(strPlugin.c_str());
6157 if (RT_FAILURE(vrc))
6158 throw setError(VBOX_E_NOT_SUPPORTED,
6159 tr("Retrieving encryption settings of the image failed because the encryption plugin could not be loaded (%s)"),
6160 i_vdError(vrc).c_str());
6161 }
6162 else
6163 throw setError(VBOX_E_NOT_SUPPORTED,
6164 tr("Encryption is not supported because the extension pack '%s' is missing the encryption plugin (old extension pack installed?)"),
6165 ORACLE_PUEL_EXTPACK_NAME);
6166 }
6167 else
6168 throw setError(VBOX_E_NOT_SUPPORTED,
6169 tr("Encryption is not supported because the extension pack '%s' is missing"),
6170 ORACLE_PUEL_EXTPACK_NAME);
6171#else
6172 throw setError(VBOX_E_NOT_SUPPORTED,
6173 tr("Encryption is not supported because extension pack support is not built in"));
6174#endif
6175
6176 if (itKeyId == pBase->m->mapProperties.end())
6177 throw setError(VBOX_E_INVALID_OBJECT_STATE,
6178 tr("Image '%s' is configured for encryption but doesn't has a key identifier set"),
6179 pBase->m->strLocationFull.c_str());
6180
6181 /* Find the proper secret key in the key store. */
6182 if (!pKeyStore)
6183 throw setError(VBOX_E_INVALID_OBJECT_STATE,
6184 tr("Image '%s' is configured for encryption but there is no key store to retrieve the password from"),
6185 pBase->m->strLocationFull.c_str());
6186
6187 SecretKey *pKey = NULL;
6188 vrc = pKeyStore->retainSecretKey(itKeyId->second, &pKey);
6189 if (RT_FAILURE(vrc))
6190 throw setError(VBOX_E_INVALID_OBJECT_STATE,
6191 tr("Failed to retrieve the secret key with ID \"%s\" from the store (%Rrc)"),
6192 itKeyId->second.c_str(), vrc);
6193
6194 Medium::CryptoFilterSettings CryptoSettingsRead;
6195 i_taskEncryptSettingsSetup(&CryptoSettingsRead, NULL, itKeyStore->second.c_str(), (const char *)pKey->getKeyBuffer(),
6196 false /* fCreateKeyStore */);
6197 vrc = VDFilterAdd(hdd, "CRYPT", VD_FILTER_FLAGS_READ, CryptoSettingsRead.vdFilterIfaces);
6198 pKeyStore->releaseSecretKey(itKeyId->second);
6199 if (vrc == VERR_VD_PASSWORD_INCORRECT)
6200 throw setError(VBOX_E_PASSWORD_INCORRECT, tr("The password to decrypt the image is incorrect"));
6201 if (RT_FAILURE(vrc))
6202 throw setError(VBOX_E_INVALID_OBJECT_STATE, tr("Failed to load the decryption filter: %s"),
6203 i_vdError(vrc).c_str());
6204 }
6205
6206 /* Open all media in the source chain. */
6207 MediumLockList::Base::const_iterator sourceListBegin = SourceMediumLockList.GetBegin();
6208 MediumLockList::Base::const_iterator sourceListEnd = SourceMediumLockList.GetEnd();
6209 for (MediumLockList::Base::const_iterator it = sourceListBegin; it != sourceListEnd; ++it)
6210 {
6211 const MediumLock &mediumLock = *it;
6212 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6213 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6214
6215 /* sanity check */
6216 Assert(pMedium->m->state == MediumState_LockedRead);
6217
6218 /* Open all media in read-only mode. */
6219 vrc = VDOpen(hdd,
6220 pMedium->m->strFormat.c_str(),
6221 pMedium->m->strLocationFull.c_str(),
6222 VD_OPEN_FLAGS_READONLY | m->uOpenFlagsDef,
6223 pMedium->m->vdImageIfaces);
6224 if (RT_FAILURE(vrc))
6225 throw setError(VBOX_E_FILE_ERROR,
6226 tr("Could not open the medium storage unit '%s'%s"),
6227 pMedium->m->strLocationFull.c_str(),
6228 i_vdError(vrc).c_str());
6229 }
6230
6231 Assert(m->state == MediumState_LockedRead);
6232
6233 /* unlock before the potentially lengthy operation */
6234 thisLock.release();
6235
6236 /*
6237 * Create a VFS file interface to the HDD and attach a progress wrapper
6238 * that monitors the progress reading of the raw image. The image will
6239 * be read twice if hVfsFssDst does sparse processing.
6240 */
6241 RTVFSFILE hVfsFileDisk = NIL_RTVFSFILE;
6242 vrc = VDCreateVfsFileFromDisk(hdd, 0 /*fFlags*/, &hVfsFileDisk);
6243 if (RT_SUCCESS(vrc))
6244 {
6245 RTVFSFILE hVfsFileProgress = NIL_RTVFSFILE;
6246 vrc = RTVfsCreateProgressForFile(hVfsFileDisk, aProgress->i_iprtProgressCallback, &*aProgress,
6247 RTVFSPROGRESS_F_CANCELABLE | RTVFSPROGRESS_F_FORWARD_SEEK_AS_READ,
6248 VDGetSize(hdd, VD_LAST_IMAGE) * (fSparse ? 2 : 1) /*cbExpectedRead*/,
6249 0 /*cbExpectedWritten*/, &hVfsFileProgress);
6250 RTVfsFileRelease(hVfsFileDisk);
6251 if (RT_SUCCESS(vrc))
6252 {
6253 RTVFSOBJ hVfsObj = RTVfsObjFromFile(hVfsFileProgress);
6254 RTVfsFileRelease(hVfsFileProgress);
6255
6256 vrc = RTVfsFsStrmAdd(hVfsFssDst, aFilename, hVfsObj, 0 /*fFlags*/);
6257 RTVfsObjRelease(hVfsObj);
6258 if (RT_FAILURE(vrc))
6259 rc = setErrorBoth(VBOX_E_FILE_ERROR, vrc, tr("Failed to add '%s' to output (%Rrc)"), aFilename, vrc);
6260
6261 }
6262 else
6263 rc = setErrorBoth(VBOX_E_FILE_ERROR, vrc,
6264 tr("RTVfsCreateProgressForFile failed when processing '%s' (%Rrc)"), aFilename, vrc);
6265 }
6266 else
6267 rc = setErrorBoth(VBOX_E_FILE_ERROR, vrc, tr("VDCreateVfsFileFromDisk failed for '%s' (%Rrc)"), aFilename, vrc);
6268 }
6269 catch (HRESULT hrc3) { rc = hrc3; }
6270
6271 VDDestroy(hdd);
6272 }
6273 catch (HRESULT hrc2) { rc = hrc2; }
6274
6275 /* Everything is explicitly unlocked when the task exits,
6276 * as the task destruction also destroys the source chain. */
6277
6278 /* Make sure the source chain is released early, otherwise it can
6279 * lead to deadlocks with concurrent IAppliance activities. */
6280 SourceMediumLockList.Clear();
6281
6282 return rc;
6283}
6284
6285/**
6286 * Used by IAppliance to export disk images.
6287 *
6288 * @param aFilename Filename to create (UTF8).
6289 * @param aFormat Medium format for creating @a aFilename.
6290 * @param aVariant Which exact image format variant to use for the
6291 * destination image.
6292 * @param pKeyStore The optional key store for decrypting the data for
6293 * encrypted media during the export.
6294 * @param aVDImageIOIf Pointer to the callback table for a VDINTERFACEIO
6295 * interface. May be NULL.
6296 * @param aVDImageIOUser Opaque data for the callbacks.
6297 * @param aProgress Progress object to use.
6298 * @return
6299 * @note The source format is defined by the Medium instance.
6300 *
6301 * @todo The only consumer of this method (Appliance::i_writeFSImpl) is already
6302 * on a worker thread, so perhaps consider bypassing the thread here and
6303 * run in the task synchronously? VBoxSVC has enough threads as it is...
6304 */
6305HRESULT Medium::i_exportFile(const char *aFilename,
6306 const ComObjPtr<MediumFormat> &aFormat,
6307 MediumVariant_T aVariant,
6308 SecretKeyStore *pKeyStore,
6309#ifdef VBOX_WITH_NEW_TAR_CREATOR
6310 RTVFSIOSTREAM hVfsIosDst,
6311#else
6312 PVDINTERFACEIO aVDImageIOIf, void *aVDImageIOUser,
6313#endif
6314 const ComObjPtr<Progress> &aProgress)
6315{
6316 AssertPtrReturn(aFilename, E_INVALIDARG);
6317 AssertReturn(!aFormat.isNull(), E_INVALIDARG);
6318 AssertReturn(!aProgress.isNull(), E_INVALIDARG);
6319
6320 AutoCaller autoCaller(this);
6321 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6322
6323 HRESULT rc = S_OK;
6324 Medium::Task *pTask = NULL;
6325
6326 try
6327 {
6328 // This needs no extra locks besides what is done in the called methods.
6329
6330 /* Build the source lock list. */
6331 MediumLockList *pSourceMediumLockList(new MediumLockList());
6332 rc = i_createMediumLockList(true /* fFailIfInaccessible */,
6333 NULL /* pToLockWrite */,
6334 false /* fMediumLockWriteAll */,
6335 NULL,
6336 *pSourceMediumLockList);
6337 if (FAILED(rc))
6338 {
6339 delete pSourceMediumLockList;
6340 throw rc;
6341 }
6342
6343 rc = pSourceMediumLockList->Lock();
6344 if (FAILED(rc))
6345 {
6346 delete pSourceMediumLockList;
6347 throw setError(rc,
6348 tr("Failed to lock source media '%s'"),
6349 i_getLocationFull().c_str());
6350 }
6351
6352 /* setup task object to carry out the operation asynchronously */
6353 pTask = new Medium::ExportTask(this, aProgress, aFilename, aFormat, aVariant,
6354#ifdef VBOX_WITH_NEW_TAR_CREATOR
6355 pKeyStore, hVfsIosDst, pSourceMediumLockList);
6356#else
6357 pKeyStore, aVDImageIOIf, aVDImageIOUser, pSourceMediumLockList);
6358#endif
6359 rc = pTask->rc();
6360 AssertComRC(rc);
6361 if (FAILED(rc))
6362 throw rc;
6363 }
6364 catch (HRESULT aRC) { rc = aRC; }
6365
6366 if (SUCCEEDED(rc))
6367 rc = pTask->createThread();
6368 else if (pTask != NULL)
6369 delete pTask;
6370
6371 return rc;
6372}
6373
6374/**
6375 * Used by IAppliance to import disk images.
6376 *
6377 * @param aFilename Filename to read (UTF8).
6378 * @param aFormat Medium format for reading @a aFilename.
6379 * @param aVariant Which exact image format variant to use
6380 * for the destination image.
6381 * @param aVfsIosSrc Handle to the source I/O stream.
6382 * @param aParent Parent medium. May be NULL.
6383 * @param aProgress Progress object to use.
6384 * @return
6385 * @note The destination format is defined by the Medium instance.
6386 *
6387 * @todo The only consumer of this method (Appliance::i_importOneDiskImage) is
6388 * already on a worker thread, so perhaps consider bypassing the thread
6389 * here and run in the task synchronously? VBoxSVC has enough threads as
6390 * it is...
6391 */
6392HRESULT Medium::i_importFile(const char *aFilename,
6393 const ComObjPtr<MediumFormat> &aFormat,
6394 MediumVariant_T aVariant,
6395 RTVFSIOSTREAM aVfsIosSrc,
6396 const ComObjPtr<Medium> &aParent,
6397 const ComObjPtr<Progress> &aProgress)
6398{
6399 /** @todo r=klaus The code below needs to be double checked with regard
6400 * to lock order violations, it probably causes lock order issues related
6401 * to the AutoCaller usage. */
6402 AssertPtrReturn(aFilename, E_INVALIDARG);
6403 AssertReturn(!aFormat.isNull(), E_INVALIDARG);
6404 AssertReturn(!aProgress.isNull(), E_INVALIDARG);
6405
6406 AutoCaller autoCaller(this);
6407 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6408
6409 HRESULT rc = S_OK;
6410 Medium::Task *pTask = NULL;
6411
6412 try
6413 {
6414 // locking: we need the tree lock first because we access parent pointers
6415 // and we need to write-lock the media involved
6416 uint32_t cHandles = 2;
6417 LockHandle* pHandles[3] = { &m->pVirtualBox->i_getMediaTreeLockHandle(),
6418 this->lockHandle() };
6419 /* Only add parent to the lock if it is not null */
6420 if (!aParent.isNull())
6421 pHandles[cHandles++] = aParent->lockHandle();
6422 AutoWriteLock alock(cHandles,
6423 pHandles
6424 COMMA_LOCKVAL_SRC_POS);
6425
6426 if ( m->state != MediumState_NotCreated
6427 && m->state != MediumState_Created)
6428 throw i_setStateError();
6429
6430 /* Build the target lock list. */
6431 MediumLockList *pTargetMediumLockList(new MediumLockList());
6432 alock.release();
6433 rc = i_createMediumLockList(true /* fFailIfInaccessible */,
6434 this /* pToLockWrite */,
6435 false /* fMediumLockWriteAll */,
6436 aParent,
6437 *pTargetMediumLockList);
6438 alock.acquire();
6439 if (FAILED(rc))
6440 {
6441 delete pTargetMediumLockList;
6442 throw rc;
6443 }
6444
6445 alock.release();
6446 rc = pTargetMediumLockList->Lock();
6447 alock.acquire();
6448 if (FAILED(rc))
6449 {
6450 delete pTargetMediumLockList;
6451 throw setError(rc,
6452 tr("Failed to lock target media '%s'"),
6453 i_getLocationFull().c_str());
6454 }
6455
6456 /* setup task object to carry out the operation asynchronously */
6457 pTask = new Medium::ImportTask(this, aProgress, aFilename, aFormat, aVariant,
6458 aVfsIosSrc, aParent, pTargetMediumLockList);
6459 rc = pTask->rc();
6460 AssertComRC(rc);
6461 if (FAILED(rc))
6462 throw rc;
6463
6464 if (m->state == MediumState_NotCreated)
6465 m->state = MediumState_Creating;
6466 }
6467 catch (HRESULT aRC) { rc = aRC; }
6468
6469 if (SUCCEEDED(rc))
6470 rc = pTask->createThread();
6471 else if (pTask != NULL)
6472 delete pTask;
6473
6474 return rc;
6475}
6476
6477/**
6478 * Internal version of the public CloneTo API which allows to enable certain
6479 * optimizations to improve speed during VM cloning.
6480 *
6481 * @param aTarget Target medium
6482 * @param aVariant Which exact image format variant to use
6483 * for the destination image.
6484 * @param aParent Parent medium. May be NULL.
6485 * @param aProgress Progress object to use.
6486 * @param idxSrcImageSame The last image in the source chain which has the
6487 * same content as the given image in the destination
6488 * chain. Use UINT32_MAX to disable this optimization.
6489 * @param idxDstImageSame The last image in the destination chain which has the
6490 * same content as the given image in the source chain.
6491 * Use UINT32_MAX to disable this optimization.
6492 * @return
6493 */
6494HRESULT Medium::i_cloneToEx(const ComObjPtr<Medium> &aTarget, ULONG aVariant,
6495 const ComObjPtr<Medium> &aParent, IProgress **aProgress,
6496 uint32_t idxSrcImageSame, uint32_t idxDstImageSame)
6497{
6498 /** @todo r=klaus The code below needs to be double checked with regard
6499 * to lock order violations, it probably causes lock order issues related
6500 * to the AutoCaller usage. */
6501 CheckComArgNotNull(aTarget);
6502 CheckComArgOutPointerValid(aProgress);
6503 ComAssertRet(aTarget != this, E_INVALIDARG);
6504
6505 AutoCaller autoCaller(this);
6506 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6507
6508 HRESULT rc = S_OK;
6509 ComObjPtr<Progress> pProgress;
6510 Medium::Task *pTask = NULL;
6511
6512 try
6513 {
6514 // locking: we need the tree lock first because we access parent pointers
6515 // and we need to write-lock the media involved
6516 uint32_t cHandles = 3;
6517 LockHandle* pHandles[4] = { &m->pVirtualBox->i_getMediaTreeLockHandle(),
6518 this->lockHandle(),
6519 aTarget->lockHandle() };
6520 /* Only add parent to the lock if it is not null */
6521 if (!aParent.isNull())
6522 pHandles[cHandles++] = aParent->lockHandle();
6523 AutoWriteLock alock(cHandles,
6524 pHandles
6525 COMMA_LOCKVAL_SRC_POS);
6526
6527 if ( aTarget->m->state != MediumState_NotCreated
6528 && aTarget->m->state != MediumState_Created)
6529 throw aTarget->i_setStateError();
6530
6531 /* Build the source lock list. */
6532 MediumLockList *pSourceMediumLockList(new MediumLockList());
6533 alock.release();
6534 rc = i_createMediumLockList(true /* fFailIfInaccessible */,
6535 NULL /* pToLockWrite */,
6536 false /* fMediumLockWriteAll */,
6537 NULL,
6538 *pSourceMediumLockList);
6539 alock.acquire();
6540 if (FAILED(rc))
6541 {
6542 delete pSourceMediumLockList;
6543 throw rc;
6544 }
6545
6546 /* Build the target lock list (including the to-be parent chain). */
6547 MediumLockList *pTargetMediumLockList(new MediumLockList());
6548 alock.release();
6549 rc = aTarget->i_createMediumLockList(true /* fFailIfInaccessible */,
6550 aTarget /* pToLockWrite */,
6551 false /* fMediumLockWriteAll */,
6552 aParent,
6553 *pTargetMediumLockList);
6554 alock.acquire();
6555 if (FAILED(rc))
6556 {
6557 delete pSourceMediumLockList;
6558 delete pTargetMediumLockList;
6559 throw rc;
6560 }
6561
6562 alock.release();
6563 rc = pSourceMediumLockList->Lock();
6564 alock.acquire();
6565 if (FAILED(rc))
6566 {
6567 delete pSourceMediumLockList;
6568 delete pTargetMediumLockList;
6569 throw setError(rc,
6570 tr("Failed to lock source media '%s'"),
6571 i_getLocationFull().c_str());
6572 }
6573 alock.release();
6574 rc = pTargetMediumLockList->Lock();
6575 alock.acquire();
6576 if (FAILED(rc))
6577 {
6578 delete pSourceMediumLockList;
6579 delete pTargetMediumLockList;
6580 throw setError(rc,
6581 tr("Failed to lock target media '%s'"),
6582 aTarget->i_getLocationFull().c_str());
6583 }
6584
6585 pProgress.createObject();
6586 rc = pProgress->init(m->pVirtualBox,
6587 static_cast <IMedium *>(this),
6588 BstrFmt(tr("Creating clone medium '%s'"), aTarget->m->strLocationFull.c_str()).raw(),
6589 TRUE /* aCancelable */);
6590 if (FAILED(rc))
6591 {
6592 delete pSourceMediumLockList;
6593 delete pTargetMediumLockList;
6594 throw rc;
6595 }
6596
6597 /* setup task object to carry out the operation asynchronously */
6598 pTask = new Medium::CloneTask(this, pProgress, aTarget,
6599 (MediumVariant_T)aVariant,
6600 aParent, idxSrcImageSame,
6601 idxDstImageSame, pSourceMediumLockList,
6602 pTargetMediumLockList);
6603 rc = pTask->rc();
6604 AssertComRC(rc);
6605 if (FAILED(rc))
6606 throw rc;
6607
6608 if (aTarget->m->state == MediumState_NotCreated)
6609 aTarget->m->state = MediumState_Creating;
6610 }
6611 catch (HRESULT aRC) { rc = aRC; }
6612
6613 if (SUCCEEDED(rc))
6614 {
6615 rc = pTask->createThread();
6616
6617 if (SUCCEEDED(rc))
6618 pProgress.queryInterfaceTo(aProgress);
6619 }
6620 else if (pTask != NULL)
6621 delete pTask;
6622
6623 return rc;
6624}
6625
6626/**
6627 * Returns the key identifier for this medium if encryption is configured.
6628 *
6629 * @returns Key identifier or empty string if no encryption is configured.
6630 */
6631const Utf8Str& Medium::i_getKeyId()
6632{
6633 ComObjPtr<Medium> pBase = i_getBase();
6634
6635 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6636
6637 settings::StringsMap::const_iterator it = pBase->m->mapProperties.find("CRYPT/KeyId");
6638 if (it == pBase->m->mapProperties.end())
6639 return Utf8Str::Empty;
6640
6641 return it->second;
6642}
6643
6644/**
6645 * Returns all filter related properties.
6646 *
6647 * @returns COM status code.
6648 * @param aReturnNames Where to store the properties names on success.
6649 * @param aReturnValues Where to store the properties values on success.
6650 */
6651HRESULT Medium::i_getFilterProperties(std::vector<com::Utf8Str> &aReturnNames,
6652 std::vector<com::Utf8Str> &aReturnValues)
6653{
6654 std::vector<com::Utf8Str> aPropNames;
6655 std::vector<com::Utf8Str> aPropValues;
6656 HRESULT hrc = getProperties(Utf8Str(""), aPropNames, aPropValues);
6657
6658 if (SUCCEEDED(hrc))
6659 {
6660 unsigned cReturnSize = 0;
6661 aReturnNames.resize(0);
6662 aReturnValues.resize(0);
6663 for (unsigned idx = 0; idx < aPropNames.size(); idx++)
6664 {
6665 if (i_isPropertyForFilter(aPropNames[idx]))
6666 {
6667 aReturnNames.resize(cReturnSize + 1);
6668 aReturnValues.resize(cReturnSize + 1);
6669 aReturnNames[cReturnSize] = aPropNames[idx];
6670 aReturnValues[cReturnSize] = aPropValues[idx];
6671 cReturnSize++;
6672 }
6673 }
6674 }
6675
6676 return hrc;
6677}
6678
6679/**
6680 * Preparation to move this medium to a new location
6681 *
6682 * @param aLocation Location of the storage unit. If the location is a FS-path,
6683 * then it can be relative to the VirtualBox home directory.
6684 *
6685 * @note Must be called from under this object's write lock.
6686 */
6687HRESULT Medium::i_preparationForMoving(const Utf8Str &aLocation)
6688{
6689 HRESULT rc = E_FAIL;
6690
6691 if (i_getLocationFull() != aLocation)
6692 {
6693 m->strNewLocationFull = aLocation;
6694 m->fMoveThisMedium = true;
6695 rc = S_OK;
6696 }
6697
6698 return rc;
6699}
6700
6701/**
6702 * Checking whether current operation "moving" or not
6703 */
6704bool Medium::i_isMoveOperation(const ComObjPtr<Medium> &aTarget) const
6705{
6706 RT_NOREF(aTarget);
6707 return (m->fMoveThisMedium == true) ? true:false;
6708}
6709
6710bool Medium::i_resetMoveOperationData()
6711{
6712 m->strNewLocationFull.setNull();
6713 m->fMoveThisMedium = false;
6714 return true;
6715}
6716
6717Utf8Str Medium::i_getNewLocationForMoving() const
6718{
6719 if (m->fMoveThisMedium == true)
6720 return m->strNewLocationFull;
6721 else
6722 return Utf8Str();
6723}
6724////////////////////////////////////////////////////////////////////////////////
6725//
6726// Private methods
6727//
6728////////////////////////////////////////////////////////////////////////////////
6729
6730/**
6731 * Queries information from the medium.
6732 *
6733 * As a result of this call, the accessibility state and data members such as
6734 * size and description will be updated with the current information.
6735 *
6736 * @note This method may block during a system I/O call that checks storage
6737 * accessibility.
6738 *
6739 * @note Caller MUST NOT hold the media tree or medium lock.
6740 *
6741 * @note Locks m->pParent for reading. Locks this object for writing.
6742 *
6743 * @param fSetImageId Whether to reset the UUID contained in the image file
6744 * to the UUID in the medium instance data (see SetIDs())
6745 * @param fSetParentId Whether to reset the parent UUID contained in the image
6746 * file to the parent UUID in the medium instance data (see
6747 * SetIDs())
6748 * @param autoCaller
6749 * @return
6750 */
6751HRESULT Medium::i_queryInfo(bool fSetImageId, bool fSetParentId, AutoCaller &autoCaller)
6752{
6753 Assert(!isWriteLockOnCurrentThread());
6754 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6755
6756 if ( ( m->state != MediumState_Created
6757 && m->state != MediumState_Inaccessible
6758 && m->state != MediumState_LockedRead)
6759 || m->fClosing)
6760 return E_FAIL;
6761
6762 HRESULT rc = S_OK;
6763
6764 int vrc = VINF_SUCCESS;
6765
6766 /* check if a blocking i_queryInfo() call is in progress on some other thread,
6767 * and wait for it to finish if so instead of querying data ourselves */
6768 if (m->queryInfoRunning)
6769 {
6770 Assert( m->state == MediumState_LockedRead
6771 || m->state == MediumState_LockedWrite);
6772
6773 while (m->queryInfoRunning)
6774 {
6775 alock.release();
6776 /* must not hold the object lock now */
6777 Assert(!isWriteLockOnCurrentThread());
6778 {
6779 AutoReadLock qlock(m->queryInfoSem COMMA_LOCKVAL_SRC_POS);
6780 }
6781 alock.acquire();
6782 }
6783
6784 return S_OK;
6785 }
6786
6787 bool success = false;
6788 Utf8Str lastAccessError;
6789
6790 /* are we dealing with a new medium constructed using the existing
6791 * location? */
6792 bool isImport = m->id.isZero();
6793 unsigned uOpenFlags = VD_OPEN_FLAGS_INFO;
6794
6795 /* Note that we don't use VD_OPEN_FLAGS_READONLY when opening new
6796 * media because that would prevent necessary modifications
6797 * when opening media of some third-party formats for the first
6798 * time in VirtualBox (such as VMDK for which VDOpen() needs to
6799 * generate an UUID if it is missing) */
6800 if ( m->hddOpenMode == OpenReadOnly
6801 || m->type == MediumType_Readonly
6802 || (!isImport && !fSetImageId && !fSetParentId)
6803 )
6804 uOpenFlags |= VD_OPEN_FLAGS_READONLY;
6805
6806 /* Open shareable medium with the appropriate flags */
6807 if (m->type == MediumType_Shareable)
6808 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
6809
6810 /* Lock the medium, which makes the behavior much more consistent, must be
6811 * done before dropping the object lock and setting queryInfoRunning. */
6812 ComPtr<IToken> pToken;
6813 if (uOpenFlags & (VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_SHAREABLE))
6814 rc = LockRead(pToken.asOutParam());
6815 else
6816 rc = LockWrite(pToken.asOutParam());
6817 if (FAILED(rc)) return rc;
6818
6819 /* Copies of the input state fields which are not read-only,
6820 * as we're dropping the lock. CAUTION: be extremely careful what
6821 * you do with the contents of this medium object, as you will
6822 * create races if there are concurrent changes. */
6823 Utf8Str format(m->strFormat);
6824 Utf8Str location(m->strLocationFull);
6825 ComObjPtr<MediumFormat> formatObj = m->formatObj;
6826
6827 /* "Output" values which can't be set because the lock isn't held
6828 * at the time the values are determined. */
6829 Guid mediumId = m->id;
6830 uint64_t mediumSize = 0;
6831 uint64_t mediumLogicalSize = 0;
6832
6833 /* Flag whether a base image has a non-zero parent UUID and thus
6834 * need repairing after it was closed again. */
6835 bool fRepairImageZeroParentUuid = false;
6836
6837 ComObjPtr<VirtualBox> pVirtualBox = m->pVirtualBox;
6838
6839 /* must be set before leaving the object lock the first time */
6840 m->queryInfoRunning = true;
6841
6842 /* must leave object lock now, because a lock from a higher lock class
6843 * is needed and also a lengthy operation is coming */
6844 alock.release();
6845 autoCaller.release();
6846
6847 /* Note that taking the queryInfoSem after leaving the object lock above
6848 * can lead to short spinning of the loops waiting for i_queryInfo() to
6849 * complete. This is unavoidable since the other order causes a lock order
6850 * violation: here it would be requesting the object lock (at the beginning
6851 * of the method), then queryInfoSem, and below the other way round. */
6852 AutoWriteLock qlock(m->queryInfoSem COMMA_LOCKVAL_SRC_POS);
6853
6854 /* take the opportunity to have a media tree lock, released initially */
6855 Assert(!isWriteLockOnCurrentThread());
6856 Assert(!pVirtualBox->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
6857 AutoWriteLock treeLock(pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
6858 treeLock.release();
6859
6860 /* re-take the caller, but not the object lock, to keep uninit away */
6861 autoCaller.add();
6862 if (FAILED(autoCaller.rc()))
6863 {
6864 m->queryInfoRunning = false;
6865 return autoCaller.rc();
6866 }
6867
6868 try
6869 {
6870 /* skip accessibility checks for host drives */
6871 if (m->hostDrive)
6872 {
6873 success = true;
6874 throw S_OK;
6875 }
6876
6877 PVDISK hdd;
6878 vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
6879 ComAssertRCThrow(vrc, E_FAIL);
6880
6881 try
6882 {
6883 /** @todo This kind of opening of media is assuming that diff
6884 * media can be opened as base media. Should be documented that
6885 * it must work for all medium format backends. */
6886 vrc = VDOpen(hdd,
6887 format.c_str(),
6888 location.c_str(),
6889 uOpenFlags | m->uOpenFlagsDef,
6890 m->vdImageIfaces);
6891 if (RT_FAILURE(vrc))
6892 {
6893 lastAccessError = Utf8StrFmt(tr("Could not open the medium '%s'%s"),
6894 location.c_str(), i_vdError(vrc).c_str());
6895 throw S_OK;
6896 }
6897
6898 if (formatObj->i_getCapabilities() & MediumFormatCapabilities_Uuid)
6899 {
6900 /* Modify the UUIDs if necessary. The associated fields are
6901 * not modified by other code, so no need to copy. */
6902 if (fSetImageId)
6903 {
6904 alock.acquire();
6905 vrc = VDSetUuid(hdd, 0, m->uuidImage.raw());
6906 alock.release();
6907 if (RT_FAILURE(vrc))
6908 {
6909 lastAccessError = Utf8StrFmt(tr("Could not update the UUID of medium '%s'%s"),
6910 location.c_str(), i_vdError(vrc).c_str());
6911 throw S_OK;
6912 }
6913 mediumId = m->uuidImage;
6914 }
6915 if (fSetParentId)
6916 {
6917 alock.acquire();
6918 vrc = VDSetParentUuid(hdd, 0, m->uuidParentImage.raw());
6919 alock.release();
6920 if (RT_FAILURE(vrc))
6921 {
6922 lastAccessError = Utf8StrFmt(tr("Could not update the parent UUID of medium '%s'%s"),
6923 location.c_str(), i_vdError(vrc).c_str());
6924 throw S_OK;
6925 }
6926 }
6927 /* zap the information, these are no long-term members */
6928 alock.acquire();
6929 unconst(m->uuidImage).clear();
6930 unconst(m->uuidParentImage).clear();
6931 alock.release();
6932
6933 /* check the UUID */
6934 RTUUID uuid;
6935 vrc = VDGetUuid(hdd, 0, &uuid);
6936 ComAssertRCThrow(vrc, E_FAIL);
6937
6938 if (isImport)
6939 {
6940 mediumId = uuid;
6941
6942 if (mediumId.isZero() && (m->hddOpenMode == OpenReadOnly))
6943 // only when importing a VDMK that has no UUID, create one in memory
6944 mediumId.create();
6945 }
6946 else
6947 {
6948 Assert(!mediumId.isZero());
6949
6950 if (mediumId != uuid)
6951 {
6952 /** @todo r=klaus this always refers to VirtualBox.xml as the medium registry, even for new VMs */
6953 lastAccessError = Utf8StrFmt(
6954 tr("UUID {%RTuuid} of the medium '%s' does not match the value {%RTuuid} stored in the media registry ('%s')"),
6955 &uuid,
6956 location.c_str(),
6957 mediumId.raw(),
6958 pVirtualBox->i_settingsFilePath().c_str());
6959 throw S_OK;
6960 }
6961 }
6962 }
6963 else
6964 {
6965 /* the backend does not support storing UUIDs within the
6966 * underlying storage so use what we store in XML */
6967
6968 if (fSetImageId)
6969 {
6970 /* set the UUID if an API client wants to change it */
6971 alock.acquire();
6972 mediumId = m->uuidImage;
6973 alock.release();
6974 }
6975 else if (isImport)
6976 {
6977 /* generate an UUID for an imported UUID-less medium */
6978 mediumId.create();
6979 }
6980 }
6981
6982 /* set the image uuid before the below parent uuid handling code
6983 * might place it somewhere in the media tree, so that the medium
6984 * UUID is valid at this point */
6985 alock.acquire();
6986 if (isImport || fSetImageId)
6987 unconst(m->id) = mediumId;
6988 alock.release();
6989
6990 /* get the medium variant */
6991 unsigned uImageFlags;
6992 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
6993 ComAssertRCThrow(vrc, E_FAIL);
6994 alock.acquire();
6995 m->variant = (MediumVariant_T)uImageFlags;
6996 alock.release();
6997
6998 /* check/get the parent uuid and update corresponding state */
6999 if (uImageFlags & VD_IMAGE_FLAGS_DIFF)
7000 {
7001 RTUUID parentId;
7002 vrc = VDGetParentUuid(hdd, 0, &parentId);
7003 ComAssertRCThrow(vrc, E_FAIL);
7004
7005 /* streamOptimized VMDK images are only accepted as base
7006 * images, as this allows automatic repair of OVF appliances.
7007 * Since such images don't support random writes they will not
7008 * be created for diff images. Only an overly smart user might
7009 * manually create this case. Too bad for him. */
7010 if ( (isImport || fSetParentId)
7011 && !(uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
7012 {
7013 /* the parent must be known to us. Note that we freely
7014 * call locking methods of mVirtualBox and parent, as all
7015 * relevant locks must be already held. There may be no
7016 * concurrent access to the just opened medium on other
7017 * threads yet (and init() will fail if this method reports
7018 * MediumState_Inaccessible) */
7019
7020 ComObjPtr<Medium> pParent;
7021 if (RTUuidIsNull(&parentId))
7022 rc = VBOX_E_OBJECT_NOT_FOUND;
7023 else
7024 rc = pVirtualBox->i_findHardDiskById(Guid(parentId), false /* aSetError */, &pParent);
7025 if (FAILED(rc))
7026 {
7027 if (fSetImageId && !fSetParentId)
7028 {
7029 /* If the image UUID gets changed for an existing
7030 * image then the parent UUID can be stale. In such
7031 * cases clear the parent information. The parent
7032 * information may/will be re-set later if the
7033 * API client wants to adjust a complete medium
7034 * hierarchy one by one. */
7035 rc = S_OK;
7036 alock.acquire();
7037 RTUuidClear(&parentId);
7038 vrc = VDSetParentUuid(hdd, 0, &parentId);
7039 alock.release();
7040 ComAssertRCThrow(vrc, E_FAIL);
7041 }
7042 else
7043 {
7044 lastAccessError = Utf8StrFmt(tr("Parent medium with UUID {%RTuuid} of the medium '%s' is not found in the media registry ('%s')"),
7045 &parentId, location.c_str(),
7046 pVirtualBox->i_settingsFilePath().c_str());
7047 throw S_OK;
7048 }
7049 }
7050
7051 /* must drop the caller before taking the tree lock */
7052 autoCaller.release();
7053 /* we set m->pParent & children() */
7054 treeLock.acquire();
7055 autoCaller.add();
7056 if (FAILED(autoCaller.rc()))
7057 throw autoCaller.rc();
7058
7059 if (m->pParent)
7060 i_deparent();
7061
7062 if (!pParent.isNull())
7063 if (pParent->i_getDepth() >= SETTINGS_MEDIUM_DEPTH_MAX)
7064 {
7065 AutoReadLock plock(pParent COMMA_LOCKVAL_SRC_POS);
7066 throw setError(VBOX_E_INVALID_OBJECT_STATE,
7067 tr("Cannot open differencing image for medium '%s', because it exceeds the medium tree depth limit. Please merge some images which you no longer need"),
7068 pParent->m->strLocationFull.c_str());
7069 }
7070 i_setParent(pParent);
7071
7072 treeLock.release();
7073 }
7074 else
7075 {
7076 /* must drop the caller before taking the tree lock */
7077 autoCaller.release();
7078 /* we access m->pParent */
7079 treeLock.acquire();
7080 autoCaller.add();
7081 if (FAILED(autoCaller.rc()))
7082 throw autoCaller.rc();
7083
7084 /* check that parent UUIDs match. Note that there's no need
7085 * for the parent's AutoCaller (our lifetime is bound to
7086 * it) */
7087
7088 if (m->pParent.isNull())
7089 {
7090 /* Due to a bug in VDCopy() in VirtualBox 3.0.0-3.0.14
7091 * and 3.1.0-3.1.8 there are base images out there
7092 * which have a non-zero parent UUID. No point in
7093 * complaining about them, instead automatically
7094 * repair the problem. Later we can bring back the
7095 * error message, but we should wait until really
7096 * most users have repaired their images, either with
7097 * VBoxFixHdd or this way. */
7098#if 1
7099 fRepairImageZeroParentUuid = true;
7100#else /* 0 */
7101 lastAccessError = Utf8StrFmt(
7102 tr("Medium type of '%s' is differencing but it is not associated with any parent medium in the media registry ('%s')"),
7103 location.c_str(),
7104 pVirtualBox->settingsFilePath().c_str());
7105 treeLock.release();
7106 throw S_OK;
7107#endif /* 0 */
7108 }
7109
7110 {
7111 autoCaller.release();
7112 AutoReadLock parentLock(m->pParent COMMA_LOCKVAL_SRC_POS);
7113 autoCaller.add();
7114 if (FAILED(autoCaller.rc()))
7115 throw autoCaller.rc();
7116
7117 if ( !fRepairImageZeroParentUuid
7118 && m->pParent->i_getState() != MediumState_Inaccessible
7119 && m->pParent->i_getId() != parentId)
7120 {
7121 /** @todo r=klaus this always refers to VirtualBox.xml as the medium registry, even for new VMs */
7122 lastAccessError = Utf8StrFmt(
7123 tr("Parent UUID {%RTuuid} of the medium '%s' does not match UUID {%RTuuid} of its parent medium stored in the media registry ('%s')"),
7124 &parentId, location.c_str(),
7125 m->pParent->i_getId().raw(),
7126 pVirtualBox->i_settingsFilePath().c_str());
7127 parentLock.release();
7128 treeLock.release();
7129 throw S_OK;
7130 }
7131 }
7132
7133 /// @todo NEWMEDIA what to do if the parent is not
7134 /// accessible while the diff is? Probably nothing. The
7135 /// real code will detect the mismatch anyway.
7136
7137 treeLock.release();
7138 }
7139 }
7140
7141 mediumSize = VDGetFileSize(hdd, 0);
7142 mediumLogicalSize = VDGetSize(hdd, 0);
7143
7144 success = true;
7145 }
7146 catch (HRESULT aRC)
7147 {
7148 rc = aRC;
7149 }
7150
7151 vrc = VDDestroy(hdd);
7152 if (RT_FAILURE(vrc))
7153 {
7154 lastAccessError = Utf8StrFmt(tr("Could not update and close the medium '%s'%s"),
7155 location.c_str(), i_vdError(vrc).c_str());
7156 success = false;
7157 throw S_OK;
7158 }
7159 }
7160 catch (HRESULT aRC)
7161 {
7162 rc = aRC;
7163 }
7164
7165 autoCaller.release();
7166 treeLock.acquire();
7167 autoCaller.add();
7168 if (FAILED(autoCaller.rc()))
7169 {
7170 m->queryInfoRunning = false;
7171 return autoCaller.rc();
7172 }
7173 alock.acquire();
7174
7175 if (success)
7176 {
7177 m->size = mediumSize;
7178 m->logicalSize = mediumLogicalSize;
7179 m->strLastAccessError.setNull();
7180 }
7181 else
7182 {
7183 m->strLastAccessError = lastAccessError;
7184 Log1WarningFunc(("'%s' is not accessible (error='%s', rc=%Rhrc, vrc=%Rrc)\n",
7185 location.c_str(), m->strLastAccessError.c_str(), rc, vrc));
7186 }
7187
7188 /* Set the proper state according to the result of the check */
7189 if (success)
7190 m->preLockState = MediumState_Created;
7191 else
7192 m->preLockState = MediumState_Inaccessible;
7193
7194 /* unblock anyone waiting for the i_queryInfo results */
7195 qlock.release();
7196 m->queryInfoRunning = false;
7197
7198 pToken->Abandon();
7199 pToken.setNull();
7200
7201 if (FAILED(rc)) return rc;
7202
7203 /* If this is a base image which incorrectly has a parent UUID set,
7204 * repair the image now by zeroing the parent UUID. This is only done
7205 * when we have structural information from a config file, on import
7206 * this is not possible. If someone would accidentally call openMedium
7207 * with a diff image before the base is registered this would destroy
7208 * the diff. Not acceptable. */
7209 if (fRepairImageZeroParentUuid)
7210 {
7211 rc = LockWrite(pToken.asOutParam());
7212 if (FAILED(rc)) return rc;
7213
7214 alock.release();
7215
7216 try
7217 {
7218 PVDISK hdd;
7219 vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
7220 ComAssertRCThrow(vrc, E_FAIL);
7221
7222 try
7223 {
7224 vrc = VDOpen(hdd,
7225 format.c_str(),
7226 location.c_str(),
7227 (uOpenFlags & ~VD_OPEN_FLAGS_READONLY) | m->uOpenFlagsDef,
7228 m->vdImageIfaces);
7229 if (RT_FAILURE(vrc))
7230 throw S_OK;
7231
7232 RTUUID zeroParentUuid;
7233 RTUuidClear(&zeroParentUuid);
7234 vrc = VDSetParentUuid(hdd, 0, &zeroParentUuid);
7235 ComAssertRCThrow(vrc, E_FAIL);
7236 }
7237 catch (HRESULT aRC)
7238 {
7239 rc = aRC;
7240 }
7241
7242 VDDestroy(hdd);
7243 }
7244 catch (HRESULT aRC)
7245 {
7246 rc = aRC;
7247 }
7248
7249 pToken->Abandon();
7250 pToken.setNull();
7251 if (FAILED(rc)) return rc;
7252 }
7253
7254 return rc;
7255}
7256
7257/**
7258 * Performs extra checks if the medium can be closed and returns S_OK in
7259 * this case. Otherwise, returns a respective error message. Called by
7260 * Close() under the medium tree lock and the medium lock.
7261 *
7262 * @note Also reused by Medium::Reset().
7263 *
7264 * @note Caller must hold the media tree write lock!
7265 */
7266HRESULT Medium::i_canClose()
7267{
7268 Assert(m->pVirtualBox->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
7269
7270 if (i_getChildren().size() != 0)
7271 return setError(VBOX_E_OBJECT_IN_USE,
7272 tr("Cannot close medium '%s' because it has %d child media"),
7273 m->strLocationFull.c_str(), i_getChildren().size());
7274
7275 return S_OK;
7276}
7277
7278/**
7279 * Unregisters this medium with mVirtualBox. Called by close() under the medium tree lock.
7280 *
7281 * @note Caller must have locked the media tree lock for writing!
7282 */
7283HRESULT Medium::i_unregisterWithVirtualBox()
7284{
7285 /* Note that we need to de-associate ourselves from the parent to let
7286 * VirtualBox::i_unregisterMedium() properly save the registry */
7287
7288 /* we modify m->pParent and access children */
7289 Assert(m->pVirtualBox->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
7290
7291 Medium *pParentBackup = m->pParent;
7292 AssertReturn(i_getChildren().size() == 0, E_FAIL);
7293 if (m->pParent)
7294 i_deparent();
7295
7296 HRESULT rc = m->pVirtualBox->i_unregisterMedium(this);
7297 if (FAILED(rc))
7298 {
7299 if (pParentBackup)
7300 {
7301 // re-associate with the parent as we are still relatives in the registry
7302 i_setParent(pParentBackup);
7303 }
7304 }
7305
7306 return rc;
7307}
7308
7309/**
7310 * Like SetProperty but do not trigger a settings store. Only for internal use!
7311 */
7312HRESULT Medium::i_setPropertyDirect(const Utf8Str &aName, const Utf8Str &aValue)
7313{
7314 AutoCaller autoCaller(this);
7315 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7316
7317 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
7318
7319 switch (m->state)
7320 {
7321 case MediumState_Created:
7322 case MediumState_Inaccessible:
7323 break;
7324 default:
7325 return i_setStateError();
7326 }
7327
7328 m->mapProperties[aName] = aValue;
7329
7330 return S_OK;
7331}
7332
7333/**
7334 * Sets the extended error info according to the current media state.
7335 *
7336 * @note Must be called from under this object's write or read lock.
7337 */
7338HRESULT Medium::i_setStateError()
7339{
7340 HRESULT rc = E_FAIL;
7341
7342 switch (m->state)
7343 {
7344 case MediumState_NotCreated:
7345 {
7346 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
7347 tr("Storage for the medium '%s' is not created"),
7348 m->strLocationFull.c_str());
7349 break;
7350 }
7351 case MediumState_Created:
7352 {
7353 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
7354 tr("Storage for the medium '%s' is already created"),
7355 m->strLocationFull.c_str());
7356 break;
7357 }
7358 case MediumState_LockedRead:
7359 {
7360 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
7361 tr("Medium '%s' is locked for reading by another task"),
7362 m->strLocationFull.c_str());
7363 break;
7364 }
7365 case MediumState_LockedWrite:
7366 {
7367 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
7368 tr("Medium '%s' is locked for writing by another task"),
7369 m->strLocationFull.c_str());
7370 break;
7371 }
7372 case MediumState_Inaccessible:
7373 {
7374 /* be in sync with Console::powerUpThread() */
7375 if (!m->strLastAccessError.isEmpty())
7376 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
7377 tr("Medium '%s' is not accessible. %s"),
7378 m->strLocationFull.c_str(), m->strLastAccessError.c_str());
7379 else
7380 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
7381 tr("Medium '%s' is not accessible"),
7382 m->strLocationFull.c_str());
7383 break;
7384 }
7385 case MediumState_Creating:
7386 {
7387 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
7388 tr("Storage for the medium '%s' is being created"),
7389 m->strLocationFull.c_str());
7390 break;
7391 }
7392 case MediumState_Deleting:
7393 {
7394 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
7395 tr("Storage for the medium '%s' is being deleted"),
7396 m->strLocationFull.c_str());
7397 break;
7398 }
7399 default:
7400 {
7401 AssertFailed();
7402 break;
7403 }
7404 }
7405
7406 return rc;
7407}
7408
7409/**
7410 * Sets the value of m->strLocationFull. The given location must be a fully
7411 * qualified path; relative paths are not supported here.
7412 *
7413 * As a special exception, if the specified location is a file path that ends with '/'
7414 * then the file name part will be generated by this method automatically in the format
7415 * '{\<uuid\>}.\<ext\>' where \<uuid\> is a fresh UUID that this method will generate
7416 * and assign to this medium, and \<ext\> is the default extension for this
7417 * medium's storage format. Note that this procedure requires the media state to
7418 * be NotCreated and will return a failure otherwise.
7419 *
7420 * @param aLocation Location of the storage unit. If the location is a FS-path,
7421 * then it can be relative to the VirtualBox home directory.
7422 * @param aFormat Optional fallback format if it is an import and the format
7423 * cannot be determined.
7424 *
7425 * @note Must be called from under this object's write lock.
7426 */
7427HRESULT Medium::i_setLocation(const Utf8Str &aLocation,
7428 const Utf8Str &aFormat /* = Utf8Str::Empty */)
7429{
7430 AssertReturn(!aLocation.isEmpty(), E_FAIL);
7431
7432 AutoCaller autoCaller(this);
7433 AssertComRCReturnRC(autoCaller.rc());
7434
7435 /* formatObj may be null only when initializing from an existing path and
7436 * no format is known yet */
7437 AssertReturn( (!m->strFormat.isEmpty() && !m->formatObj.isNull())
7438 || ( getObjectState().getState() == ObjectState::InInit
7439 && m->state != MediumState_NotCreated
7440 && m->id.isZero()
7441 && m->strFormat.isEmpty()
7442 && m->formatObj.isNull()),
7443 E_FAIL);
7444
7445 /* are we dealing with a new medium constructed using the existing
7446 * location? */
7447 bool isImport = m->strFormat.isEmpty();
7448
7449 if ( isImport
7450 || ( (m->formatObj->i_getCapabilities() & MediumFormatCapabilities_File)
7451 && !m->hostDrive))
7452 {
7453 Guid id;
7454
7455 Utf8Str locationFull(aLocation);
7456
7457 if (m->state == MediumState_NotCreated)
7458 {
7459 /* must be a file (formatObj must be already known) */
7460 Assert(m->formatObj->i_getCapabilities() & MediumFormatCapabilities_File);
7461
7462 if (RTPathFilename(aLocation.c_str()) == NULL)
7463 {
7464 /* no file name is given (either an empty string or ends with a
7465 * slash), generate a new UUID + file name if the state allows
7466 * this */
7467
7468 ComAssertMsgRet(!m->formatObj->i_getFileExtensions().empty(),
7469 ("Must be at least one extension if it is MediumFormatCapabilities_File\n"),
7470 E_FAIL);
7471
7472 Utf8Str strExt = m->formatObj->i_getFileExtensions().front();
7473 ComAssertMsgRet(!strExt.isEmpty(),
7474 ("Default extension must not be empty\n"),
7475 E_FAIL);
7476
7477 id.create();
7478
7479 locationFull = Utf8StrFmt("%s{%RTuuid}.%s",
7480 aLocation.c_str(), id.raw(), strExt.c_str());
7481 }
7482 }
7483
7484 // we must always have full paths now (if it refers to a file)
7485 if ( ( m->formatObj.isNull()
7486 || m->formatObj->i_getCapabilities() & MediumFormatCapabilities_File)
7487 && !RTPathStartsWithRoot(locationFull.c_str()))
7488 return setError(VBOX_E_FILE_ERROR,
7489 tr("The given path '%s' is not fully qualified"),
7490 locationFull.c_str());
7491
7492 /* detect the backend from the storage unit if importing */
7493 if (isImport)
7494 {
7495 VDTYPE enmType = VDTYPE_INVALID;
7496 char *backendName = NULL;
7497
7498 int vrc = VINF_SUCCESS;
7499
7500 /* is it a file? */
7501 {
7502 RTFILE file;
7503 vrc = RTFileOpen(&file, locationFull.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
7504 if (RT_SUCCESS(vrc))
7505 RTFileClose(file);
7506 }
7507 if (RT_SUCCESS(vrc))
7508 {
7509 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
7510 locationFull.c_str(), &backendName, &enmType);
7511 }
7512 else if ( vrc != VERR_FILE_NOT_FOUND
7513 && vrc != VERR_PATH_NOT_FOUND
7514 && vrc != VERR_ACCESS_DENIED
7515 && locationFull != aLocation)
7516 {
7517 /* assume it's not a file, restore the original location */
7518 locationFull = aLocation;
7519 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
7520 locationFull.c_str(), &backendName, &enmType);
7521 }
7522
7523 if (RT_FAILURE(vrc))
7524 {
7525 if (vrc == VERR_ACCESS_DENIED)
7526 return setError(VBOX_E_FILE_ERROR,
7527 tr("Permission problem accessing the file for the medium '%s' (%Rrc)"),
7528 locationFull.c_str(), vrc);
7529 else if (vrc == VERR_FILE_NOT_FOUND || vrc == VERR_PATH_NOT_FOUND)
7530 return setError(VBOX_E_FILE_ERROR,
7531 tr("Could not find file for the medium '%s' (%Rrc)"),
7532 locationFull.c_str(), vrc);
7533 else if (aFormat.isEmpty())
7534 return setError(VBOX_E_IPRT_ERROR,
7535 tr("Could not get the storage format of the medium '%s' (%Rrc)"),
7536 locationFull.c_str(), vrc);
7537 else
7538 {
7539 HRESULT rc = i_setFormat(aFormat);
7540 /* setFormat() must not fail since we've just used the backend so
7541 * the format object must be there */
7542 AssertComRCReturnRC(rc);
7543 }
7544 }
7545 else if ( enmType == VDTYPE_INVALID
7546 || m->devType != i_convertToDeviceType(enmType))
7547 {
7548 /*
7549 * The user tried to use a image as a device which is not supported
7550 * by the backend.
7551 */
7552 return setError(E_FAIL,
7553 tr("The medium '%s' can't be used as the requested device type"),
7554 locationFull.c_str());
7555 }
7556 else
7557 {
7558 ComAssertRet(backendName != NULL && *backendName != '\0', E_FAIL);
7559
7560 HRESULT rc = i_setFormat(backendName);
7561 RTStrFree(backendName);
7562
7563 /* setFormat() must not fail since we've just used the backend so
7564 * the format object must be there */
7565 AssertComRCReturnRC(rc);
7566 }
7567 }
7568
7569 m->strLocationFull = locationFull;
7570
7571 /* is it still a file? */
7572 if ( (m->formatObj->i_getCapabilities() & MediumFormatCapabilities_File)
7573 && (m->state == MediumState_NotCreated)
7574 )
7575 /* assign a new UUID (this UUID will be used when calling
7576 * VDCreateBase/VDCreateDiff as a wanted UUID). Note that we
7577 * also do that if we didn't generate it to make sure it is
7578 * either generated by us or reset to null */
7579 unconst(m->id) = id;
7580 }
7581 else
7582 m->strLocationFull = aLocation;
7583
7584 return S_OK;
7585}
7586
7587/**
7588 * Checks that the format ID is valid and sets it on success.
7589 *
7590 * Note that this method will caller-reference the format object on success!
7591 * This reference must be released somewhere to let the MediumFormat object be
7592 * uninitialized.
7593 *
7594 * @note Must be called from under this object's write lock.
7595 */
7596HRESULT Medium::i_setFormat(const Utf8Str &aFormat)
7597{
7598 /* get the format object first */
7599 {
7600 SystemProperties *pSysProps = m->pVirtualBox->i_getSystemProperties();
7601 AutoReadLock propsLock(pSysProps COMMA_LOCKVAL_SRC_POS);
7602
7603 unconst(m->formatObj) = pSysProps->i_mediumFormat(aFormat);
7604 if (m->formatObj.isNull())
7605 return setError(E_INVALIDARG,
7606 tr("Invalid medium storage format '%s'"),
7607 aFormat.c_str());
7608
7609 /* get properties (preinsert them as keys in the map). Note that the
7610 * map doesn't grow over the object life time since the set of
7611 * properties is meant to be constant. */
7612
7613 Assert(m->mapProperties.empty());
7614
7615 for (MediumFormat::PropertyArray::const_iterator it = m->formatObj->i_getProperties().begin();
7616 it != m->formatObj->i_getProperties().end();
7617 ++it)
7618 {
7619 m->mapProperties.insert(std::make_pair(it->strName, Utf8Str::Empty));
7620 }
7621 }
7622
7623 unconst(m->strFormat) = aFormat;
7624
7625 return S_OK;
7626}
7627
7628/**
7629 * Converts the Medium device type to the VD type.
7630 */
7631VDTYPE Medium::i_convertDeviceType()
7632{
7633 VDTYPE enmType;
7634
7635 switch (m->devType)
7636 {
7637 case DeviceType_HardDisk:
7638 enmType = VDTYPE_HDD;
7639 break;
7640 case DeviceType_DVD:
7641 enmType = VDTYPE_OPTICAL_DISC;
7642 break;
7643 case DeviceType_Floppy:
7644 enmType = VDTYPE_FLOPPY;
7645 break;
7646 default:
7647 ComAssertFailedRet(VDTYPE_INVALID);
7648 }
7649
7650 return enmType;
7651}
7652
7653/**
7654 * Converts from the VD type to the medium type.
7655 */
7656DeviceType_T Medium::i_convertToDeviceType(VDTYPE enmType)
7657{
7658 DeviceType_T devType;
7659
7660 switch (enmType)
7661 {
7662 case VDTYPE_HDD:
7663 devType = DeviceType_HardDisk;
7664 break;
7665 case VDTYPE_OPTICAL_DISC:
7666 devType = DeviceType_DVD;
7667 break;
7668 case VDTYPE_FLOPPY:
7669 devType = DeviceType_Floppy;
7670 break;
7671 default:
7672 ComAssertFailedRet(DeviceType_Null);
7673 }
7674
7675 return devType;
7676}
7677
7678/**
7679 * Internal method which checks whether a property name is for a filter plugin.
7680 */
7681bool Medium::i_isPropertyForFilter(const com::Utf8Str &aName)
7682{
7683 /* If the name contains "/" use the part before as a filter name and lookup the filter. */
7684 size_t offSlash;
7685 if ((offSlash = aName.find("/", 0)) != aName.npos)
7686 {
7687 com::Utf8Str strFilter;
7688 com::Utf8Str strKey;
7689
7690 HRESULT rc = strFilter.assignEx(aName, 0, offSlash);
7691 if (FAILED(rc))
7692 return false;
7693
7694 rc = strKey.assignEx(aName, offSlash + 1, aName.length() - offSlash - 1); /* Skip slash */
7695 if (FAILED(rc))
7696 return false;
7697
7698 VDFILTERINFO FilterInfo;
7699 int vrc = VDFilterInfoOne(strFilter.c_str(), &FilterInfo);
7700 if (RT_SUCCESS(vrc))
7701 {
7702 /* Check that the property exists. */
7703 PCVDCONFIGINFO paConfig = FilterInfo.paConfigInfo;
7704 while (paConfig->pszKey)
7705 {
7706 if (strKey.equals(paConfig->pszKey))
7707 return true;
7708 paConfig++;
7709 }
7710 }
7711 }
7712
7713 return false;
7714}
7715
7716/**
7717 * Returns the last error message collected by the i_vdErrorCall callback and
7718 * resets it.
7719 *
7720 * The error message is returned prepended with a dot and a space, like this:
7721 * <code>
7722 * ". <error_text> (%Rrc)"
7723 * </code>
7724 * to make it easily appendable to a more general error message. The @c %Rrc
7725 * format string is given @a aVRC as an argument.
7726 *
7727 * If there is no last error message collected by i_vdErrorCall or if it is a
7728 * null or empty string, then this function returns the following text:
7729 * <code>
7730 * " (%Rrc)"
7731 * </code>
7732 *
7733 * @note Doesn't do any object locking; it is assumed that the caller makes sure
7734 * the callback isn't called by more than one thread at a time.
7735 *
7736 * @param aVRC VBox error code to use when no error message is provided.
7737 */
7738Utf8Str Medium::i_vdError(int aVRC)
7739{
7740 Utf8Str error;
7741
7742 if (m->vdError.isEmpty())
7743 error = Utf8StrFmt(" (%Rrc)", aVRC);
7744 else
7745 error = Utf8StrFmt(".\n%s", m->vdError.c_str());
7746
7747 m->vdError.setNull();
7748
7749 return error;
7750}
7751
7752/**
7753 * Error message callback.
7754 *
7755 * Puts the reported error message to the m->vdError field.
7756 *
7757 * @note Doesn't do any object locking; it is assumed that the caller makes sure
7758 * the callback isn't called by more than one thread at a time.
7759 *
7760 * @param pvUser The opaque data passed on container creation.
7761 * @param rc The VBox error code.
7762 * @param SRC_POS Use RT_SRC_POS.
7763 * @param pszFormat Error message format string.
7764 * @param va Error message arguments.
7765 */
7766/*static*/
7767DECLCALLBACK(void) Medium::i_vdErrorCall(void *pvUser, int rc, RT_SRC_POS_DECL,
7768 const char *pszFormat, va_list va)
7769{
7770 NOREF(pszFile); NOREF(iLine); NOREF(pszFunction); /* RT_SRC_POS_DECL */
7771
7772 Medium *that = static_cast<Medium*>(pvUser);
7773 AssertReturnVoid(that != NULL);
7774
7775 if (that->m->vdError.isEmpty())
7776 that->m->vdError =
7777 Utf8StrFmt("%s (%Rrc)", Utf8Str(pszFormat, va).c_str(), rc);
7778 else
7779 that->m->vdError =
7780 Utf8StrFmt("%s.\n%s (%Rrc)", that->m->vdError.c_str(),
7781 Utf8Str(pszFormat, va).c_str(), rc);
7782}
7783
7784/* static */
7785DECLCALLBACK(bool) Medium::i_vdConfigAreKeysValid(void *pvUser,
7786 const char * /* pszzValid */)
7787{
7788 Medium *that = static_cast<Medium*>(pvUser);
7789 AssertReturn(that != NULL, false);
7790
7791 /* we always return true since the only keys we have are those found in
7792 * VDBACKENDINFO */
7793 return true;
7794}
7795
7796/* static */
7797DECLCALLBACK(int) Medium::i_vdConfigQuerySize(void *pvUser,
7798 const char *pszName,
7799 size_t *pcbValue)
7800{
7801 AssertReturn(VALID_PTR(pcbValue), VERR_INVALID_POINTER);
7802
7803 Medium *that = static_cast<Medium*>(pvUser);
7804 AssertReturn(that != NULL, VERR_GENERAL_FAILURE);
7805
7806 settings::StringsMap::const_iterator it = that->m->mapProperties.find(Utf8Str(pszName));
7807 if (it == that->m->mapProperties.end())
7808 return VERR_CFGM_VALUE_NOT_FOUND;
7809
7810 /* we interpret null values as "no value" in Medium */
7811 if (it->second.isEmpty())
7812 return VERR_CFGM_VALUE_NOT_FOUND;
7813
7814 *pcbValue = it->second.length() + 1 /* include terminator */;
7815
7816 return VINF_SUCCESS;
7817}
7818
7819/* static */
7820DECLCALLBACK(int) Medium::i_vdConfigQuery(void *pvUser,
7821 const char *pszName,
7822 char *pszValue,
7823 size_t cchValue)
7824{
7825 AssertReturn(VALID_PTR(pszValue), VERR_INVALID_POINTER);
7826
7827 Medium *that = static_cast<Medium*>(pvUser);
7828 AssertReturn(that != NULL, VERR_GENERAL_FAILURE);
7829
7830 settings::StringsMap::const_iterator it = that->m->mapProperties.find(Utf8Str(pszName));
7831 if (it == that->m->mapProperties.end())
7832 return VERR_CFGM_VALUE_NOT_FOUND;
7833
7834 /* we interpret null values as "no value" in Medium */
7835 if (it->second.isEmpty())
7836 return VERR_CFGM_VALUE_NOT_FOUND;
7837
7838 const Utf8Str &value = it->second;
7839 if (value.length() >= cchValue)
7840 return VERR_CFGM_NOT_ENOUGH_SPACE;
7841
7842 memcpy(pszValue, value.c_str(), value.length() + 1);
7843
7844 return VINF_SUCCESS;
7845}
7846
7847DECLCALLBACK(int) Medium::i_vdTcpSocketCreate(uint32_t fFlags, PVDSOCKET pSock)
7848{
7849 PVDSOCKETINT pSocketInt = NULL;
7850
7851 if ((fFlags & VD_INTERFACETCPNET_CONNECT_EXTENDED_SELECT) != 0)
7852 return VERR_NOT_SUPPORTED;
7853
7854 pSocketInt = (PVDSOCKETINT)RTMemAllocZ(sizeof(VDSOCKETINT));
7855 if (!pSocketInt)
7856 return VERR_NO_MEMORY;
7857
7858 pSocketInt->hSocket = NIL_RTSOCKET;
7859 *pSock = pSocketInt;
7860 return VINF_SUCCESS;
7861}
7862
7863DECLCALLBACK(int) Medium::i_vdTcpSocketDestroy(VDSOCKET Sock)
7864{
7865 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7866
7867 if (pSocketInt->hSocket != NIL_RTSOCKET)
7868 RTTcpClientCloseEx(pSocketInt->hSocket, false /*fGracefulShutdown*/);
7869
7870 RTMemFree(pSocketInt);
7871
7872 return VINF_SUCCESS;
7873}
7874
7875DECLCALLBACK(int) Medium::i_vdTcpClientConnect(VDSOCKET Sock, const char *pszAddress, uint32_t uPort,
7876 RTMSINTERVAL cMillies)
7877{
7878 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7879
7880 return RTTcpClientConnectEx(pszAddress, uPort, &pSocketInt->hSocket, cMillies, NULL);
7881}
7882
7883DECLCALLBACK(int) Medium::i_vdTcpClientClose(VDSOCKET Sock)
7884{
7885 int rc = VINF_SUCCESS;
7886 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7887
7888 rc = RTTcpClientCloseEx(pSocketInt->hSocket, false /*fGracefulShutdown*/);
7889 pSocketInt->hSocket = NIL_RTSOCKET;
7890 return rc;
7891}
7892
7893DECLCALLBACK(bool) Medium::i_vdTcpIsClientConnected(VDSOCKET Sock)
7894{
7895 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7896 return pSocketInt->hSocket != NIL_RTSOCKET;
7897}
7898
7899DECLCALLBACK(int) Medium::i_vdTcpSelectOne(VDSOCKET Sock, RTMSINTERVAL cMillies)
7900{
7901 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7902 return RTTcpSelectOne(pSocketInt->hSocket, cMillies);
7903}
7904
7905DECLCALLBACK(int) Medium::i_vdTcpRead(VDSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
7906{
7907 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7908 return RTTcpRead(pSocketInt->hSocket, pvBuffer, cbBuffer, pcbRead);
7909}
7910
7911DECLCALLBACK(int) Medium::i_vdTcpWrite(VDSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
7912{
7913 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7914 return RTTcpWrite(pSocketInt->hSocket, pvBuffer, cbBuffer);
7915}
7916
7917DECLCALLBACK(int) Medium::i_vdTcpSgWrite(VDSOCKET Sock, PCRTSGBUF pSgBuf)
7918{
7919 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7920 return RTTcpSgWrite(pSocketInt->hSocket, pSgBuf);
7921}
7922
7923DECLCALLBACK(int) Medium::i_vdTcpFlush(VDSOCKET Sock)
7924{
7925 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7926 return RTTcpFlush(pSocketInt->hSocket);
7927}
7928
7929DECLCALLBACK(int) Medium::i_vdTcpSetSendCoalescing(VDSOCKET Sock, bool fEnable)
7930{
7931 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7932 return RTTcpSetSendCoalescing(pSocketInt->hSocket, fEnable);
7933}
7934
7935DECLCALLBACK(int) Medium::i_vdTcpGetLocalAddress(VDSOCKET Sock, PRTNETADDR pAddr)
7936{
7937 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7938 return RTTcpGetLocalAddress(pSocketInt->hSocket, pAddr);
7939}
7940
7941DECLCALLBACK(int) Medium::i_vdTcpGetPeerAddress(VDSOCKET Sock, PRTNETADDR pAddr)
7942{
7943 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7944 return RTTcpGetPeerAddress(pSocketInt->hSocket, pAddr);
7945}
7946
7947DECLCALLBACK(bool) Medium::i_vdCryptoConfigAreKeysValid(void *pvUser, const char *pszzValid)
7948{
7949 /* Just return always true here. */
7950 NOREF(pvUser);
7951 NOREF(pszzValid);
7952 return true;
7953}
7954
7955DECLCALLBACK(int) Medium::i_vdCryptoConfigQuerySize(void *pvUser, const char *pszName, size_t *pcbValue)
7956{
7957 Medium::CryptoFilterSettings *pSettings = (Medium::CryptoFilterSettings *)pvUser;
7958 AssertPtrReturn(pSettings, VERR_GENERAL_FAILURE);
7959 AssertReturn(VALID_PTR(pcbValue), VERR_INVALID_POINTER);
7960
7961 size_t cbValue = 0;
7962 if (!strcmp(pszName, "Algorithm"))
7963 cbValue = strlen(pSettings->pszCipher) + 1;
7964 else if (!strcmp(pszName, "KeyId"))
7965 cbValue = sizeof("irrelevant");
7966 else if (!strcmp(pszName, "KeyStore"))
7967 {
7968 if (!pSettings->pszKeyStoreLoad)
7969 return VERR_CFGM_VALUE_NOT_FOUND;
7970 cbValue = strlen(pSettings->pszKeyStoreLoad) + 1;
7971 }
7972 else if (!strcmp(pszName, "CreateKeyStore"))
7973 cbValue = 2; /* Single digit + terminator. */
7974 else
7975 return VERR_CFGM_VALUE_NOT_FOUND;
7976
7977 *pcbValue = cbValue + 1 /* include terminator */;
7978
7979 return VINF_SUCCESS;
7980}
7981
7982DECLCALLBACK(int) Medium::i_vdCryptoConfigQuery(void *pvUser, const char *pszName,
7983 char *pszValue, size_t cchValue)
7984{
7985 Medium::CryptoFilterSettings *pSettings = (Medium::CryptoFilterSettings *)pvUser;
7986 AssertPtrReturn(pSettings, VERR_GENERAL_FAILURE);
7987 AssertReturn(VALID_PTR(pszValue), VERR_INVALID_POINTER);
7988
7989 const char *psz = NULL;
7990 if (!strcmp(pszName, "Algorithm"))
7991 psz = pSettings->pszCipher;
7992 else if (!strcmp(pszName, "KeyId"))
7993 psz = "irrelevant";
7994 else if (!strcmp(pszName, "KeyStore"))
7995 psz = pSettings->pszKeyStoreLoad;
7996 else if (!strcmp(pszName, "CreateKeyStore"))
7997 {
7998 if (pSettings->fCreateKeyStore)
7999 psz = "1";
8000 else
8001 psz = "0";
8002 }
8003 else
8004 return VERR_CFGM_VALUE_NOT_FOUND;
8005
8006 size_t cch = strlen(psz);
8007 if (cch >= cchValue)
8008 return VERR_CFGM_NOT_ENOUGH_SPACE;
8009
8010 memcpy(pszValue, psz, cch + 1);
8011 return VINF_SUCCESS;
8012}
8013
8014DECLCALLBACK(int) Medium::i_vdCryptoKeyRetain(void *pvUser, const char *pszId,
8015 const uint8_t **ppbKey, size_t *pcbKey)
8016{
8017 Medium::CryptoFilterSettings *pSettings = (Medium::CryptoFilterSettings *)pvUser;
8018 NOREF(pszId);
8019 NOREF(ppbKey);
8020 NOREF(pcbKey);
8021 AssertPtrReturn(pSettings, VERR_GENERAL_FAILURE);
8022 AssertMsgFailedReturn(("This method should not be called here!\n"), VERR_INVALID_STATE);
8023}
8024
8025DECLCALLBACK(int) Medium::i_vdCryptoKeyRelease(void *pvUser, const char *pszId)
8026{
8027 Medium::CryptoFilterSettings *pSettings = (Medium::CryptoFilterSettings *)pvUser;
8028 NOREF(pszId);
8029 AssertPtrReturn(pSettings, VERR_GENERAL_FAILURE);
8030 AssertMsgFailedReturn(("This method should not be called here!\n"), VERR_INVALID_STATE);
8031}
8032
8033DECLCALLBACK(int) Medium::i_vdCryptoKeyStorePasswordRetain(void *pvUser, const char *pszId, const char **ppszPassword)
8034{
8035 Medium::CryptoFilterSettings *pSettings = (Medium::CryptoFilterSettings *)pvUser;
8036 AssertPtrReturn(pSettings, VERR_GENERAL_FAILURE);
8037
8038 NOREF(pszId);
8039 *ppszPassword = pSettings->pszPassword;
8040 return VINF_SUCCESS;
8041}
8042
8043DECLCALLBACK(int) Medium::i_vdCryptoKeyStorePasswordRelease(void *pvUser, const char *pszId)
8044{
8045 Medium::CryptoFilterSettings *pSettings = (Medium::CryptoFilterSettings *)pvUser;
8046 AssertPtrReturn(pSettings, VERR_GENERAL_FAILURE);
8047 NOREF(pszId);
8048 return VINF_SUCCESS;
8049}
8050
8051DECLCALLBACK(int) Medium::i_vdCryptoKeyStoreSave(void *pvUser, const void *pvKeyStore, size_t cbKeyStore)
8052{
8053 Medium::CryptoFilterSettings *pSettings = (Medium::CryptoFilterSettings *)pvUser;
8054 AssertPtrReturn(pSettings, VERR_GENERAL_FAILURE);
8055
8056 pSettings->pszKeyStore = (char *)RTMemAllocZ(cbKeyStore);
8057 if (!pSettings->pszKeyStore)
8058 return VERR_NO_MEMORY;
8059
8060 memcpy(pSettings->pszKeyStore, pvKeyStore, cbKeyStore);
8061 return VINF_SUCCESS;
8062}
8063
8064DECLCALLBACK(int) Medium::i_vdCryptoKeyStoreReturnParameters(void *pvUser, const char *pszCipher,
8065 const uint8_t *pbDek, size_t cbDek)
8066{
8067 Medium::CryptoFilterSettings *pSettings = (Medium::CryptoFilterSettings *)pvUser;
8068 AssertPtrReturn(pSettings, VERR_GENERAL_FAILURE);
8069
8070 pSettings->pszCipherReturned = RTStrDup(pszCipher);
8071 pSettings->pbDek = pbDek;
8072 pSettings->cbDek = cbDek;
8073
8074 return pSettings->pszCipherReturned ? VINF_SUCCESS : VERR_NO_MEMORY;
8075}
8076
8077/**
8078 * Implementation code for the "create base" task.
8079 *
8080 * This only gets started from Medium::CreateBaseStorage() and always runs
8081 * asynchronously. As a result, we always save the VirtualBox.xml file when
8082 * we're done here.
8083 *
8084 * @param task
8085 * @return
8086 */
8087HRESULT Medium::i_taskCreateBaseHandler(Medium::CreateBaseTask &task)
8088{
8089 /** @todo r=klaus The code below needs to be double checked with regard
8090 * to lock order violations, it probably causes lock order issues related
8091 * to the AutoCaller usage. */
8092 HRESULT rc = S_OK;
8093
8094 /* these parameters we need after creation */
8095 uint64_t size = 0, logicalSize = 0;
8096 MediumVariant_T variant = MediumVariant_Standard;
8097 bool fGenerateUuid = false;
8098
8099 try
8100 {
8101 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
8102
8103 /* The object may request a specific UUID (through a special form of
8104 * the setLocation() argument). Otherwise we have to generate it */
8105 Guid id = m->id;
8106
8107 fGenerateUuid = id.isZero();
8108 if (fGenerateUuid)
8109 {
8110 id.create();
8111 /* VirtualBox::i_registerMedium() will need UUID */
8112 unconst(m->id) = id;
8113 }
8114
8115 Utf8Str format(m->strFormat);
8116 Utf8Str location(m->strLocationFull);
8117 uint64_t capabilities = m->formatObj->i_getCapabilities();
8118 ComAssertThrow(capabilities & ( MediumFormatCapabilities_CreateFixed
8119 | MediumFormatCapabilities_CreateDynamic), E_FAIL);
8120 Assert(m->state == MediumState_Creating);
8121
8122 PVDISK hdd;
8123 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
8124 ComAssertRCThrow(vrc, E_FAIL);
8125
8126 /* unlock before the potentially lengthy operation */
8127 thisLock.release();
8128
8129 try
8130 {
8131 /* ensure the directory exists */
8132 if (capabilities & MediumFormatCapabilities_File)
8133 {
8134 rc = VirtualBox::i_ensureFilePathExists(location, !(task.mVariant & MediumVariant_NoCreateDir) /* fCreate */);
8135 if (FAILED(rc))
8136 throw rc;
8137 }
8138
8139 VDGEOMETRY geo = { 0, 0, 0 }; /* auto-detect */
8140
8141 vrc = VDCreateBase(hdd,
8142 format.c_str(),
8143 location.c_str(),
8144 task.mSize,
8145 task.mVariant & ~MediumVariant_NoCreateDir,
8146 NULL,
8147 &geo,
8148 &geo,
8149 id.raw(),
8150 VD_OPEN_FLAGS_NORMAL | m->uOpenFlagsDef,
8151 m->vdImageIfaces,
8152 task.mVDOperationIfaces);
8153 if (RT_FAILURE(vrc))
8154 {
8155 if (vrc == VERR_VD_INVALID_TYPE)
8156 throw setError(VBOX_E_FILE_ERROR,
8157 tr("Parameters for creating the medium storage unit '%s' are invalid%s"),
8158 location.c_str(), i_vdError(vrc).c_str());
8159 else
8160 throw setError(VBOX_E_FILE_ERROR,
8161 tr("Could not create the medium storage unit '%s'%s"),
8162 location.c_str(), i_vdError(vrc).c_str());
8163 }
8164
8165 size = VDGetFileSize(hdd, 0);
8166 logicalSize = VDGetSize(hdd, 0);
8167 unsigned uImageFlags;
8168 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
8169 if (RT_SUCCESS(vrc))
8170 variant = (MediumVariant_T)uImageFlags;
8171 }
8172 catch (HRESULT aRC) { rc = aRC; }
8173
8174 VDDestroy(hdd);
8175 }
8176 catch (HRESULT aRC) { rc = aRC; }
8177
8178 if (SUCCEEDED(rc))
8179 {
8180 /* register with mVirtualBox as the last step and move to
8181 * Created state only on success (leaving an orphan file is
8182 * better than breaking media registry consistency) */
8183 AutoWriteLock treeLock(m->pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
8184 ComObjPtr<Medium> pMedium;
8185 rc = m->pVirtualBox->i_registerMedium(this, &pMedium, treeLock);
8186 Assert(pMedium == NULL || this == pMedium);
8187 }
8188
8189 // re-acquire the lock before changing state
8190 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
8191
8192 if (SUCCEEDED(rc))
8193 {
8194 m->state = MediumState_Created;
8195
8196 m->size = size;
8197 m->logicalSize = logicalSize;
8198 m->variant = variant;
8199
8200 thisLock.release();
8201 i_markRegistriesModified();
8202 if (task.isAsync())
8203 {
8204 // in asynchronous mode, save settings now
8205 m->pVirtualBox->i_saveModifiedRegistries();
8206 }
8207 }
8208 else
8209 {
8210 /* back to NotCreated on failure */
8211 m->state = MediumState_NotCreated;
8212
8213 /* reset UUID to prevent it from being reused next time */
8214 if (fGenerateUuid)
8215 unconst(m->id).clear();
8216 }
8217
8218 return rc;
8219}
8220
8221/**
8222 * Implementation code for the "create diff" task.
8223 *
8224 * This task always gets started from Medium::createDiffStorage() and can run
8225 * synchronously or asynchronously depending on the "wait" parameter passed to
8226 * that function. If we run synchronously, the caller expects the medium
8227 * registry modification to be set before returning; otherwise (in asynchronous
8228 * mode), we save the settings ourselves.
8229 *
8230 * @param task
8231 * @return
8232 */
8233HRESULT Medium::i_taskCreateDiffHandler(Medium::CreateDiffTask &task)
8234{
8235 /** @todo r=klaus The code below needs to be double checked with regard
8236 * to lock order violations, it probably causes lock order issues related
8237 * to the AutoCaller usage. */
8238 HRESULT rcTmp = S_OK;
8239
8240 const ComObjPtr<Medium> &pTarget = task.mTarget;
8241
8242 uint64_t size = 0, logicalSize = 0;
8243 MediumVariant_T variant = MediumVariant_Standard;
8244 bool fGenerateUuid = false;
8245
8246 try
8247 {
8248 if (i_getDepth() >= SETTINGS_MEDIUM_DEPTH_MAX)
8249 {
8250 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
8251 throw setError(VBOX_E_INVALID_OBJECT_STATE,
8252 tr("Cannot create differencing image for medium '%s', because it exceeds the medium tree depth limit. Please merge some images which you no longer need"),
8253 m->strLocationFull.c_str());
8254 }
8255
8256 /* Lock both in {parent,child} order. */
8257 AutoMultiWriteLock2 mediaLock(this, pTarget COMMA_LOCKVAL_SRC_POS);
8258
8259 /* The object may request a specific UUID (through a special form of
8260 * the setLocation() argument). Otherwise we have to generate it */
8261 Guid targetId = pTarget->m->id;
8262
8263 fGenerateUuid = targetId.isZero();
8264 if (fGenerateUuid)
8265 {
8266 targetId.create();
8267 /* VirtualBox::i_registerMedium() will need UUID */
8268 unconst(pTarget->m->id) = targetId;
8269 }
8270
8271 Guid id = m->id;
8272
8273 Utf8Str targetFormat(pTarget->m->strFormat);
8274 Utf8Str targetLocation(pTarget->m->strLocationFull);
8275 uint64_t capabilities = pTarget->m->formatObj->i_getCapabilities();
8276 ComAssertThrow(capabilities & MediumFormatCapabilities_CreateDynamic, E_FAIL);
8277
8278 Assert(pTarget->m->state == MediumState_Creating);
8279 Assert(m->state == MediumState_LockedRead);
8280
8281 PVDISK hdd;
8282 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
8283 ComAssertRCThrow(vrc, E_FAIL);
8284
8285 /* the two media are now protected by their non-default states;
8286 * unlock the media before the potentially lengthy operation */
8287 mediaLock.release();
8288
8289 try
8290 {
8291 /* Open all media in the target chain but the last. */
8292 MediumLockList::Base::const_iterator targetListBegin =
8293 task.mpMediumLockList->GetBegin();
8294 MediumLockList::Base::const_iterator targetListEnd =
8295 task.mpMediumLockList->GetEnd();
8296 for (MediumLockList::Base::const_iterator it = targetListBegin;
8297 it != targetListEnd;
8298 ++it)
8299 {
8300 const MediumLock &mediumLock = *it;
8301 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
8302
8303 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
8304
8305 /* Skip over the target diff medium */
8306 if (pMedium->m->state == MediumState_Creating)
8307 continue;
8308
8309 /* sanity check */
8310 Assert(pMedium->m->state == MediumState_LockedRead);
8311
8312 /* Open all media in appropriate mode. */
8313 vrc = VDOpen(hdd,
8314 pMedium->m->strFormat.c_str(),
8315 pMedium->m->strLocationFull.c_str(),
8316 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO | m->uOpenFlagsDef,
8317 pMedium->m->vdImageIfaces);
8318 if (RT_FAILURE(vrc))
8319 throw setError(VBOX_E_FILE_ERROR,
8320 tr("Could not open the medium storage unit '%s'%s"),
8321 pMedium->m->strLocationFull.c_str(),
8322 i_vdError(vrc).c_str());
8323 }
8324
8325 /* ensure the target directory exists */
8326 if (capabilities & MediumFormatCapabilities_File)
8327 {
8328 HRESULT rc = VirtualBox::i_ensureFilePathExists(targetLocation,
8329 !(task.mVariant & MediumVariant_NoCreateDir) /* fCreate */);
8330 if (FAILED(rc))
8331 throw rc;
8332 }
8333
8334 vrc = VDCreateDiff(hdd,
8335 targetFormat.c_str(),
8336 targetLocation.c_str(),
8337 (task.mVariant & ~MediumVariant_NoCreateDir) | VD_IMAGE_FLAGS_DIFF,
8338 NULL,
8339 targetId.raw(),
8340 id.raw(),
8341 VD_OPEN_FLAGS_NORMAL | m->uOpenFlagsDef,
8342 pTarget->m->vdImageIfaces,
8343 task.mVDOperationIfaces);
8344 if (RT_FAILURE(vrc))
8345 {
8346 if (vrc == VERR_VD_INVALID_TYPE)
8347 throw setError(VBOX_E_FILE_ERROR,
8348 tr("Parameters for creating the differencing medium storage unit '%s' are invalid%s"),
8349 targetLocation.c_str(), i_vdError(vrc).c_str());
8350 else
8351 throw setError(VBOX_E_FILE_ERROR,
8352 tr("Could not create the differencing medium storage unit '%s'%s"),
8353 targetLocation.c_str(), i_vdError(vrc).c_str());
8354 }
8355
8356 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
8357 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE);
8358 unsigned uImageFlags;
8359 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
8360 if (RT_SUCCESS(vrc))
8361 variant = (MediumVariant_T)uImageFlags;
8362 }
8363 catch (HRESULT aRC) { rcTmp = aRC; }
8364
8365 VDDestroy(hdd);
8366 }
8367 catch (HRESULT aRC) { rcTmp = aRC; }
8368
8369 MultiResult mrc(rcTmp);
8370
8371 if (SUCCEEDED(mrc))
8372 {
8373 AutoWriteLock treeLock(m->pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
8374
8375 Assert(pTarget->m->pParent.isNull());
8376
8377 /* associate child with the parent, maximum depth was checked above */
8378 pTarget->i_setParent(this);
8379
8380 /* diffs for immutable media are auto-reset by default */
8381 bool fAutoReset;
8382 {
8383 ComObjPtr<Medium> pBase = i_getBase();
8384 AutoReadLock block(pBase COMMA_LOCKVAL_SRC_POS);
8385 fAutoReset = (pBase->m->type == MediumType_Immutable);
8386 }
8387 {
8388 AutoWriteLock tlock(pTarget COMMA_LOCKVAL_SRC_POS);
8389 pTarget->m->autoReset = fAutoReset;
8390 }
8391
8392 /* register with mVirtualBox as the last step and move to
8393 * Created state only on success (leaving an orphan file is
8394 * better than breaking media registry consistency) */
8395 ComObjPtr<Medium> pMedium;
8396 mrc = m->pVirtualBox->i_registerMedium(pTarget, &pMedium, treeLock);
8397 Assert(pTarget == pMedium);
8398
8399 if (FAILED(mrc))
8400 /* break the parent association on failure to register */
8401 i_deparent();
8402 }
8403
8404 AutoMultiWriteLock2 mediaLock(this, pTarget COMMA_LOCKVAL_SRC_POS);
8405
8406 if (SUCCEEDED(mrc))
8407 {
8408 pTarget->m->state = MediumState_Created;
8409
8410 pTarget->m->size = size;
8411 pTarget->m->logicalSize = logicalSize;
8412 pTarget->m->variant = variant;
8413 }
8414 else
8415 {
8416 /* back to NotCreated on failure */
8417 pTarget->m->state = MediumState_NotCreated;
8418
8419 pTarget->m->autoReset = false;
8420
8421 /* reset UUID to prevent it from being reused next time */
8422 if (fGenerateUuid)
8423 unconst(pTarget->m->id).clear();
8424 }
8425
8426 // deregister the task registered in createDiffStorage()
8427 Assert(m->numCreateDiffTasks != 0);
8428 --m->numCreateDiffTasks;
8429
8430 mediaLock.release();
8431 i_markRegistriesModified();
8432 if (task.isAsync())
8433 {
8434 // in asynchronous mode, save settings now
8435 m->pVirtualBox->i_saveModifiedRegistries();
8436 }
8437
8438 /* Note that in sync mode, it's the caller's responsibility to
8439 * unlock the medium. */
8440
8441 return mrc;
8442}
8443
8444/**
8445 * Implementation code for the "merge" task.
8446 *
8447 * This task always gets started from Medium::mergeTo() and can run
8448 * synchronously or asynchronously depending on the "wait" parameter passed to
8449 * that function. If we run synchronously, the caller expects the medium
8450 * registry modification to be set before returning; otherwise (in asynchronous
8451 * mode), we save the settings ourselves.
8452 *
8453 * @param task
8454 * @return
8455 */
8456HRESULT Medium::i_taskMergeHandler(Medium::MergeTask &task)
8457{
8458 /** @todo r=klaus The code below needs to be double checked with regard
8459 * to lock order violations, it probably causes lock order issues related
8460 * to the AutoCaller usage. */
8461 HRESULT rcTmp = S_OK;
8462
8463 const ComObjPtr<Medium> &pTarget = task.mTarget;
8464
8465 try
8466 {
8467 if (!task.mParentForTarget.isNull())
8468 if (task.mParentForTarget->i_getDepth() >= SETTINGS_MEDIUM_DEPTH_MAX)
8469 {
8470 AutoReadLock plock(task.mParentForTarget COMMA_LOCKVAL_SRC_POS);
8471 throw setError(VBOX_E_INVALID_OBJECT_STATE,
8472 tr("Cannot merge image for medium '%s', because it exceeds the medium tree depth limit. Please merge some images which you no longer need"),
8473 task.mParentForTarget->m->strLocationFull.c_str());
8474 }
8475
8476 PVDISK hdd;
8477 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
8478 ComAssertRCThrow(vrc, E_FAIL);
8479
8480 try
8481 {
8482 // Similar code appears in SessionMachine::onlineMergeMedium, so
8483 // if you make any changes below check whether they are applicable
8484 // in that context as well.
8485
8486 unsigned uTargetIdx = VD_LAST_IMAGE;
8487 unsigned uSourceIdx = VD_LAST_IMAGE;
8488 /* Open all media in the chain. */
8489 MediumLockList::Base::iterator lockListBegin =
8490 task.mpMediumLockList->GetBegin();
8491 MediumLockList::Base::iterator lockListEnd =
8492 task.mpMediumLockList->GetEnd();
8493 unsigned i = 0;
8494 for (MediumLockList::Base::iterator it = lockListBegin;
8495 it != lockListEnd;
8496 ++it)
8497 {
8498 MediumLock &mediumLock = *it;
8499 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
8500
8501 if (pMedium == this)
8502 uSourceIdx = i;
8503 else if (pMedium == pTarget)
8504 uTargetIdx = i;
8505
8506 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
8507
8508 /*
8509 * complex sanity (sane complexity)
8510 *
8511 * The current medium must be in the Deleting (medium is merged)
8512 * or LockedRead (parent medium) state if it is not the target.
8513 * If it is the target it must be in the LockedWrite state.
8514 */
8515 Assert( ( pMedium != pTarget
8516 && ( pMedium->m->state == MediumState_Deleting
8517 || pMedium->m->state == MediumState_LockedRead))
8518 || ( pMedium == pTarget
8519 && pMedium->m->state == MediumState_LockedWrite));
8520 /*
8521 * Medium must be the target, in the LockedRead state
8522 * or Deleting state where it is not allowed to be attached
8523 * to a virtual machine.
8524 */
8525 Assert( pMedium == pTarget
8526 || pMedium->m->state == MediumState_LockedRead
8527 || ( pMedium->m->backRefs.size() == 0
8528 && pMedium->m->state == MediumState_Deleting));
8529 /* The source medium must be in Deleting state. */
8530 Assert( pMedium != this
8531 || pMedium->m->state == MediumState_Deleting);
8532
8533 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
8534
8535 if ( pMedium->m->state == MediumState_LockedRead
8536 || pMedium->m->state == MediumState_Deleting)
8537 uOpenFlags = VD_OPEN_FLAGS_READONLY;
8538 if (pMedium->m->type == MediumType_Shareable)
8539 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
8540
8541 /* Open the medium */
8542 vrc = VDOpen(hdd,
8543 pMedium->m->strFormat.c_str(),
8544 pMedium->m->strLocationFull.c_str(),
8545 uOpenFlags | m->uOpenFlagsDef,
8546 pMedium->m->vdImageIfaces);
8547 if (RT_FAILURE(vrc))
8548 throw vrc;
8549
8550 i++;
8551 }
8552
8553 ComAssertThrow( uSourceIdx != VD_LAST_IMAGE
8554 && uTargetIdx != VD_LAST_IMAGE, E_FAIL);
8555
8556 vrc = VDMerge(hdd, uSourceIdx, uTargetIdx,
8557 task.mVDOperationIfaces);
8558 if (RT_FAILURE(vrc))
8559 throw vrc;
8560
8561 /* update parent UUIDs */
8562 if (!task.mfMergeForward)
8563 {
8564 /* we need to update UUIDs of all source's children
8565 * which cannot be part of the container at once so
8566 * add each one in there individually */
8567 if (task.mpChildrenToReparent)
8568 {
8569 MediumLockList::Base::iterator childrenBegin = task.mpChildrenToReparent->GetBegin();
8570 MediumLockList::Base::iterator childrenEnd = task.mpChildrenToReparent->GetEnd();
8571 for (MediumLockList::Base::iterator it = childrenBegin;
8572 it != childrenEnd;
8573 ++it)
8574 {
8575 Medium *pMedium = it->GetMedium();
8576 /* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
8577 vrc = VDOpen(hdd,
8578 pMedium->m->strFormat.c_str(),
8579 pMedium->m->strLocationFull.c_str(),
8580 VD_OPEN_FLAGS_INFO | m->uOpenFlagsDef,
8581 pMedium->m->vdImageIfaces);
8582 if (RT_FAILURE(vrc))
8583 throw vrc;
8584
8585 vrc = VDSetParentUuid(hdd, VD_LAST_IMAGE,
8586 pTarget->m->id.raw());
8587 if (RT_FAILURE(vrc))
8588 throw vrc;
8589
8590 vrc = VDClose(hdd, false /* fDelete */);
8591 if (RT_FAILURE(vrc))
8592 throw vrc;
8593 }
8594 }
8595 }
8596 }
8597 catch (HRESULT aRC) { rcTmp = aRC; }
8598 catch (int aVRC)
8599 {
8600 rcTmp = setError(VBOX_E_FILE_ERROR,
8601 tr("Could not merge the medium '%s' to '%s'%s"),
8602 m->strLocationFull.c_str(),
8603 pTarget->m->strLocationFull.c_str(),
8604 i_vdError(aVRC).c_str());
8605 }
8606
8607 VDDestroy(hdd);
8608 }
8609 catch (HRESULT aRC) { rcTmp = aRC; }
8610
8611 ErrorInfoKeeper eik;
8612 MultiResult mrc(rcTmp);
8613 HRESULT rc2;
8614
8615 if (SUCCEEDED(mrc))
8616 {
8617 /* all media but the target were successfully deleted by
8618 * VDMerge; reparent the last one and uninitialize deleted media. */
8619
8620 AutoWriteLock treeLock(m->pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
8621
8622 if (task.mfMergeForward)
8623 {
8624 /* first, unregister the target since it may become a base
8625 * medium which needs re-registration */
8626 rc2 = m->pVirtualBox->i_unregisterMedium(pTarget);
8627 AssertComRC(rc2);
8628
8629 /* then, reparent it and disconnect the deleted branch at both ends
8630 * (chain->parent() is source's parent). Depth check above. */
8631 pTarget->i_deparent();
8632 pTarget->i_setParent(task.mParentForTarget);
8633 if (task.mParentForTarget)
8634 i_deparent();
8635
8636 /* then, register again */
8637 ComObjPtr<Medium> pMedium;
8638 rc2 = m->pVirtualBox->i_registerMedium(pTarget, &pMedium,
8639 treeLock);
8640 AssertComRC(rc2);
8641 }
8642 else
8643 {
8644 Assert(pTarget->i_getChildren().size() == 1);
8645 Medium *targetChild = pTarget->i_getChildren().front();
8646
8647 /* disconnect the deleted branch at the elder end */
8648 targetChild->i_deparent();
8649
8650 /* reparent source's children and disconnect the deleted
8651 * branch at the younger end */
8652 if (task.mpChildrenToReparent)
8653 {
8654 /* obey {parent,child} lock order */
8655 AutoWriteLock sourceLock(this COMMA_LOCKVAL_SRC_POS);
8656
8657 MediumLockList::Base::iterator childrenBegin = task.mpChildrenToReparent->GetBegin();
8658 MediumLockList::Base::iterator childrenEnd = task.mpChildrenToReparent->GetEnd();
8659 for (MediumLockList::Base::iterator it = childrenBegin;
8660 it != childrenEnd;
8661 ++it)
8662 {
8663 Medium *pMedium = it->GetMedium();
8664 AutoWriteLock childLock(pMedium COMMA_LOCKVAL_SRC_POS);
8665
8666 pMedium->i_deparent(); // removes pMedium from source
8667 // no depth check, reduces depth
8668 pMedium->i_setParent(pTarget);
8669 }
8670 }
8671 }
8672
8673 /* unregister and uninitialize all media removed by the merge */
8674 MediumLockList::Base::iterator lockListBegin =
8675 task.mpMediumLockList->GetBegin();
8676 MediumLockList::Base::iterator lockListEnd =
8677 task.mpMediumLockList->GetEnd();
8678 for (MediumLockList::Base::iterator it = lockListBegin;
8679 it != lockListEnd;
8680 )
8681 {
8682 MediumLock &mediumLock = *it;
8683 /* Create a real copy of the medium pointer, as the medium
8684 * lock deletion below would invalidate the referenced object. */
8685 const ComObjPtr<Medium> pMedium = mediumLock.GetMedium();
8686
8687 /* The target and all media not merged (readonly) are skipped */
8688 if ( pMedium == pTarget
8689 || pMedium->m->state == MediumState_LockedRead)
8690 {
8691 ++it;
8692 continue;
8693 }
8694
8695 rc2 = pMedium->m->pVirtualBox->i_unregisterMedium(pMedium);
8696 AssertComRC(rc2);
8697
8698 /* now, uninitialize the deleted medium (note that
8699 * due to the Deleting state, uninit() will not touch
8700 * the parent-child relationship so we need to
8701 * uninitialize each disk individually) */
8702
8703 /* note that the operation initiator medium (which is
8704 * normally also the source medium) is a special case
8705 * -- there is one more caller added by Task to it which
8706 * we must release. Also, if we are in sync mode, the
8707 * caller may still hold an AutoCaller instance for it
8708 * and therefore we cannot uninit() it (it's therefore
8709 * the caller's responsibility) */
8710 if (pMedium == this)
8711 {
8712 Assert(i_getChildren().size() == 0);
8713 Assert(m->backRefs.size() == 0);
8714 task.mMediumCaller.release();
8715 }
8716
8717 /* Delete the medium lock list entry, which also releases the
8718 * caller added by MergeChain before uninit() and updates the
8719 * iterator to point to the right place. */
8720 rc2 = task.mpMediumLockList->RemoveByIterator(it);
8721 AssertComRC(rc2);
8722
8723 if (task.isAsync() || pMedium != this)
8724 {
8725 treeLock.release();
8726 pMedium->uninit();
8727 treeLock.acquire();
8728 }
8729 }
8730 }
8731
8732 i_markRegistriesModified();
8733 if (task.isAsync())
8734 {
8735 // in asynchronous mode, save settings now
8736 eik.restore();
8737 m->pVirtualBox->i_saveModifiedRegistries();
8738 eik.fetch();
8739 }
8740
8741 if (FAILED(mrc))
8742 {
8743 /* Here we come if either VDMerge() failed (in which case we
8744 * assume that it tried to do everything to make a further
8745 * retry possible -- e.g. not deleted intermediate media
8746 * and so on) or VirtualBox::saveRegistries() failed (where we
8747 * should have the original tree but with intermediate storage
8748 * units deleted by VDMerge()). We have to only restore states
8749 * (through the MergeChain dtor) unless we are run synchronously
8750 * in which case it's the responsibility of the caller as stated
8751 * in the mergeTo() docs. The latter also implies that we
8752 * don't own the merge chain, so release it in this case. */
8753 if (task.isAsync())
8754 i_cancelMergeTo(task.mpChildrenToReparent, task.mpMediumLockList);
8755 }
8756
8757 return mrc;
8758}
8759
8760/**
8761 * Implementation code for the "clone" task.
8762 *
8763 * This only gets started from Medium::CloneTo() and always runs asynchronously.
8764 * As a result, we always save the VirtualBox.xml file when we're done here.
8765 *
8766 * @param task
8767 * @return
8768 */
8769HRESULT Medium::i_taskCloneHandler(Medium::CloneTask &task)
8770{
8771 /** @todo r=klaus The code below needs to be double checked with regard
8772 * to lock order violations, it probably causes lock order issues related
8773 * to the AutoCaller usage. */
8774 HRESULT rcTmp = S_OK;
8775
8776 const ComObjPtr<Medium> &pTarget = task.mTarget;
8777 const ComObjPtr<Medium> &pParent = task.mParent;
8778
8779 bool fCreatingTarget = false;
8780
8781 uint64_t size = 0, logicalSize = 0;
8782 MediumVariant_T variant = MediumVariant_Standard;
8783 bool fGenerateUuid = false;
8784
8785 try
8786 {
8787 if (!pParent.isNull())
8788 {
8789
8790 if (pParent->i_getDepth() >= SETTINGS_MEDIUM_DEPTH_MAX)
8791 {
8792 AutoReadLock plock(pParent COMMA_LOCKVAL_SRC_POS);
8793 throw setError(VBOX_E_INVALID_OBJECT_STATE,
8794 tr("Cannot clone image for medium '%s', because it exceeds the medium tree depth limit. Please merge some images which you no longer need"),
8795 pParent->m->strLocationFull.c_str());
8796 }
8797 }
8798
8799 /* Lock all in {parent,child} order. The lock is also used as a
8800 * signal from the task initiator (which releases it only after
8801 * RTThreadCreate()) that we can start the job. */
8802 AutoMultiWriteLock3 thisLock(this, pTarget, pParent COMMA_LOCKVAL_SRC_POS);
8803
8804 fCreatingTarget = pTarget->m->state == MediumState_Creating;
8805
8806 /* The object may request a specific UUID (through a special form of
8807 * the setLocation() argument). Otherwise we have to generate it */
8808 Guid targetId = pTarget->m->id;
8809
8810 fGenerateUuid = targetId.isZero();
8811 if (fGenerateUuid)
8812 {
8813 targetId.create();
8814 /* VirtualBox::registerMedium() will need UUID */
8815 unconst(pTarget->m->id) = targetId;
8816 }
8817
8818 PVDISK hdd;
8819 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
8820 ComAssertRCThrow(vrc, E_FAIL);
8821
8822 try
8823 {
8824 /* Open all media in the source chain. */
8825 MediumLockList::Base::const_iterator sourceListBegin =
8826 task.mpSourceMediumLockList->GetBegin();
8827 MediumLockList::Base::const_iterator sourceListEnd =
8828 task.mpSourceMediumLockList->GetEnd();
8829 for (MediumLockList::Base::const_iterator it = sourceListBegin;
8830 it != sourceListEnd;
8831 ++it)
8832 {
8833 const MediumLock &mediumLock = *it;
8834 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
8835 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
8836
8837 /* sanity check */
8838 Assert(pMedium->m->state == MediumState_LockedRead);
8839
8840 /** Open all media in read-only mode. */
8841 vrc = VDOpen(hdd,
8842 pMedium->m->strFormat.c_str(),
8843 pMedium->m->strLocationFull.c_str(),
8844 VD_OPEN_FLAGS_READONLY | m->uOpenFlagsDef,
8845 pMedium->m->vdImageIfaces);
8846 if (RT_FAILURE(vrc))
8847 throw setError(VBOX_E_FILE_ERROR,
8848 tr("Could not open the medium storage unit '%s'%s"),
8849 pMedium->m->strLocationFull.c_str(),
8850 i_vdError(vrc).c_str());
8851 }
8852
8853 Utf8Str targetFormat(pTarget->m->strFormat);
8854 Utf8Str targetLocation(pTarget->m->strLocationFull);
8855 uint64_t capabilities = pTarget->m->formatObj->i_getCapabilities();
8856
8857 Assert( pTarget->m->state == MediumState_Creating
8858 || pTarget->m->state == MediumState_LockedWrite);
8859 Assert(m->state == MediumState_LockedRead);
8860 Assert( pParent.isNull()
8861 || pParent->m->state == MediumState_LockedRead);
8862
8863 /* unlock before the potentially lengthy operation */
8864 thisLock.release();
8865
8866 /* ensure the target directory exists */
8867 if (capabilities & MediumFormatCapabilities_File)
8868 {
8869 HRESULT rc = VirtualBox::i_ensureFilePathExists(targetLocation,
8870 !(task.mVariant & MediumVariant_NoCreateDir) /* fCreate */);
8871 if (FAILED(rc))
8872 throw rc;
8873 }
8874
8875 PVDISK targetHdd;
8876 vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &targetHdd);
8877 ComAssertRCThrow(vrc, E_FAIL);
8878
8879 try
8880 {
8881 /* Open all media in the target chain. */
8882 MediumLockList::Base::const_iterator targetListBegin =
8883 task.mpTargetMediumLockList->GetBegin();
8884 MediumLockList::Base::const_iterator targetListEnd =
8885 task.mpTargetMediumLockList->GetEnd();
8886 for (MediumLockList::Base::const_iterator it = targetListBegin;
8887 it != targetListEnd;
8888 ++it)
8889 {
8890 const MediumLock &mediumLock = *it;
8891 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
8892
8893 /* If the target medium is not created yet there's no
8894 * reason to open it. */
8895 if (pMedium == pTarget && fCreatingTarget)
8896 continue;
8897
8898 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
8899
8900 /* sanity check */
8901 Assert( pMedium->m->state == MediumState_LockedRead
8902 || pMedium->m->state == MediumState_LockedWrite);
8903
8904 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
8905 if (pMedium->m->state != MediumState_LockedWrite)
8906 uOpenFlags = VD_OPEN_FLAGS_READONLY;
8907 if (pMedium->m->type == MediumType_Shareable)
8908 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
8909
8910 /* Open all media in appropriate mode. */
8911 vrc = VDOpen(targetHdd,
8912 pMedium->m->strFormat.c_str(),
8913 pMedium->m->strLocationFull.c_str(),
8914 uOpenFlags | m->uOpenFlagsDef,
8915 pMedium->m->vdImageIfaces);
8916 if (RT_FAILURE(vrc))
8917 throw setError(VBOX_E_FILE_ERROR,
8918 tr("Could not open the medium storage unit '%s'%s"),
8919 pMedium->m->strLocationFull.c_str(),
8920 i_vdError(vrc).c_str());
8921 }
8922
8923 /* target isn't locked, but no changing data is accessed */
8924 if (task.midxSrcImageSame == UINT32_MAX)
8925 {
8926 vrc = VDCopy(hdd,
8927 VD_LAST_IMAGE,
8928 targetHdd,
8929 targetFormat.c_str(),
8930 (fCreatingTarget) ? targetLocation.c_str() : (char *)NULL,
8931 false /* fMoveByRename */,
8932 0 /* cbSize */,
8933 task.mVariant & ~MediumVariant_NoCreateDir,
8934 targetId.raw(),
8935 VD_OPEN_FLAGS_NORMAL | m->uOpenFlagsDef,
8936 NULL /* pVDIfsOperation */,
8937 pTarget->m->vdImageIfaces,
8938 task.mVDOperationIfaces);
8939 }
8940 else
8941 {
8942 vrc = VDCopyEx(hdd,
8943 VD_LAST_IMAGE,
8944 targetHdd,
8945 targetFormat.c_str(),
8946 (fCreatingTarget) ? targetLocation.c_str() : (char *)NULL,
8947 false /* fMoveByRename */,
8948 0 /* cbSize */,
8949 task.midxSrcImageSame,
8950 task.midxDstImageSame,
8951 task.mVariant & ~MediumVariant_NoCreateDir,
8952 targetId.raw(),
8953 VD_OPEN_FLAGS_NORMAL | m->uOpenFlagsDef,
8954 NULL /* pVDIfsOperation */,
8955 pTarget->m->vdImageIfaces,
8956 task.mVDOperationIfaces);
8957 }
8958 if (RT_FAILURE(vrc))
8959 throw setError(VBOX_E_FILE_ERROR,
8960 tr("Could not create the clone medium '%s'%s"),
8961 targetLocation.c_str(), i_vdError(vrc).c_str());
8962
8963 size = VDGetFileSize(targetHdd, VD_LAST_IMAGE);
8964 logicalSize = VDGetSize(targetHdd, VD_LAST_IMAGE);
8965 unsigned uImageFlags;
8966 vrc = VDGetImageFlags(targetHdd, 0, &uImageFlags);
8967 if (RT_SUCCESS(vrc))
8968 variant = (MediumVariant_T)uImageFlags;
8969 }
8970 catch (HRESULT aRC) { rcTmp = aRC; }
8971
8972 VDDestroy(targetHdd);
8973 }
8974 catch (HRESULT aRC) { rcTmp = aRC; }
8975
8976 VDDestroy(hdd);
8977 }
8978 catch (HRESULT aRC) { rcTmp = aRC; }
8979
8980 ErrorInfoKeeper eik;
8981 MultiResult mrc(rcTmp);
8982
8983 /* Only do the parent changes for newly created media. */
8984 if (SUCCEEDED(mrc) && fCreatingTarget)
8985 {
8986 /* we set m->pParent & children() */
8987 AutoWriteLock treeLock(m->pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
8988
8989 Assert(pTarget->m->pParent.isNull());
8990
8991 if (pParent)
8992 {
8993 /* Associate the clone with the parent and deassociate
8994 * from VirtualBox. Depth check above. */
8995 pTarget->i_setParent(pParent);
8996
8997 /* register with mVirtualBox as the last step and move to
8998 * Created state only on success (leaving an orphan file is
8999 * better than breaking media registry consistency) */
9000 eik.restore();
9001 ComObjPtr<Medium> pMedium;
9002 mrc = pParent->m->pVirtualBox->i_registerMedium(pTarget, &pMedium,
9003 treeLock);
9004 Assert( FAILED(mrc)
9005 || pTarget == pMedium);
9006 eik.fetch();
9007
9008 if (FAILED(mrc))
9009 /* break parent association on failure to register */
9010 pTarget->i_deparent(); // removes target from parent
9011 }
9012 else
9013 {
9014 /* just register */
9015 eik.restore();
9016 ComObjPtr<Medium> pMedium;
9017 mrc = m->pVirtualBox->i_registerMedium(pTarget, &pMedium,
9018 treeLock);
9019 Assert( FAILED(mrc)
9020 || pTarget == pMedium);
9021 eik.fetch();
9022 }
9023 }
9024
9025 if (fCreatingTarget)
9026 {
9027 AutoWriteLock mLock(pTarget COMMA_LOCKVAL_SRC_POS);
9028
9029 if (SUCCEEDED(mrc))
9030 {
9031 pTarget->m->state = MediumState_Created;
9032
9033 pTarget->m->size = size;
9034 pTarget->m->logicalSize = logicalSize;
9035 pTarget->m->variant = variant;
9036 }
9037 else
9038 {
9039 /* back to NotCreated on failure */
9040 pTarget->m->state = MediumState_NotCreated;
9041
9042 /* reset UUID to prevent it from being reused next time */
9043 if (fGenerateUuid)
9044 unconst(pTarget->m->id).clear();
9045 }
9046 }
9047
9048 /* Copy any filter related settings over to the target. */
9049 if (SUCCEEDED(mrc))
9050 {
9051 /* Copy any filter related settings over. */
9052 ComObjPtr<Medium> pBase = i_getBase();
9053 ComObjPtr<Medium> pTargetBase = pTarget->i_getBase();
9054 std::vector<com::Utf8Str> aFilterPropNames;
9055 std::vector<com::Utf8Str> aFilterPropValues;
9056 mrc = pBase->i_getFilterProperties(aFilterPropNames, aFilterPropValues);
9057 if (SUCCEEDED(mrc))
9058 {
9059 /* Go through the properties and add them to the target medium. */
9060 for (unsigned idx = 0; idx < aFilterPropNames.size(); idx++)
9061 {
9062 mrc = pTargetBase->i_setPropertyDirect(aFilterPropNames[idx], aFilterPropValues[idx]);
9063 if (FAILED(mrc)) break;
9064 }
9065
9066 // now, at the end of this task (always asynchronous), save the settings
9067 if (SUCCEEDED(mrc))
9068 {
9069 // save the settings
9070 i_markRegistriesModified();
9071 /* collect multiple errors */
9072 eik.restore();
9073 m->pVirtualBox->i_saveModifiedRegistries();
9074 eik.fetch();
9075 }
9076 }
9077 }
9078
9079 /* Everything is explicitly unlocked when the task exits,
9080 * as the task destruction also destroys the source chain. */
9081
9082 /* Make sure the source chain is released early. It could happen
9083 * that we get a deadlock in Appliance::Import when Medium::Close
9084 * is called & the source chain is released at the same time. */
9085 task.mpSourceMediumLockList->Clear();
9086
9087 return mrc;
9088}
9089
9090/**
9091 * Implementation code for the "move" task.
9092 *
9093 * This only gets started from Medium::SetLocation() and always
9094 * runs asynchronously.
9095 *
9096 * @param task
9097 * @return
9098 */
9099HRESULT Medium::i_taskMoveHandler(Medium::MoveTask &task)
9100{
9101
9102 HRESULT rcOut = S_OK;
9103
9104 /* pTarget is equal "this" in our case */
9105 const ComObjPtr<Medium> &pTarget = task.mMedium;
9106
9107 uint64_t size = 0; NOREF(size);
9108 uint64_t logicalSize = 0; NOREF(logicalSize);
9109 MediumVariant_T variant = MediumVariant_Standard; NOREF(variant);
9110
9111 /*
9112 * it's exactly moving, not cloning
9113 */
9114 if (!i_isMoveOperation(pTarget))
9115 {
9116 HRESULT rc = setError(VBOX_E_FILE_ERROR,
9117 tr("Wrong preconditions for moving the medium %s"),
9118 pTarget->m->strLocationFull.c_str());
9119 return rc;
9120 }
9121
9122 try
9123 {
9124 /* Lock all in {parent,child} order. The lock is also used as a
9125 * signal from the task initiator (which releases it only after
9126 * RTThreadCreate()) that we can start the job. */
9127
9128 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
9129
9130 PVDISK hdd;
9131 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
9132 ComAssertRCThrow(vrc, E_FAIL);
9133
9134 try
9135 {
9136 /* Open all media in the source chain. */
9137 MediumLockList::Base::const_iterator sourceListBegin =
9138 task.mpMediumLockList->GetBegin();
9139 MediumLockList::Base::const_iterator sourceListEnd =
9140 task.mpMediumLockList->GetEnd();
9141 for (MediumLockList::Base::const_iterator it = sourceListBegin;
9142 it != sourceListEnd;
9143 ++it)
9144 {
9145 const MediumLock &mediumLock = *it;
9146 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
9147 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
9148
9149 /* sanity check */
9150 Assert(pMedium->m->state == MediumState_LockedWrite);
9151
9152 vrc = VDOpen(hdd,
9153 pMedium->m->strFormat.c_str(),
9154 pMedium->m->strLocationFull.c_str(),
9155 VD_OPEN_FLAGS_NORMAL,
9156 pMedium->m->vdImageIfaces);
9157 if (RT_FAILURE(vrc))
9158 throw setError(VBOX_E_FILE_ERROR,
9159 tr("Could not open the medium storage unit '%s'%s"),
9160 pMedium->m->strLocationFull.c_str(),
9161 i_vdError(vrc).c_str());
9162 }
9163
9164 /* we can directly use pTarget->m->"variables" but for better reading we use local copies */
9165 Guid targetId = pTarget->m->id;
9166 Utf8Str targetFormat(pTarget->m->strFormat);
9167 uint64_t targetCapabilities = pTarget->m->formatObj->i_getCapabilities();
9168
9169 /*
9170 * change target location
9171 * m->strNewLocationFull has been set already together with m->fMoveThisMedium in
9172 * i_preparationForMoving()
9173 */
9174 Utf8Str targetLocation = i_getNewLocationForMoving();
9175
9176 /* unlock before the potentially lengthy operation */
9177 thisLock.release();
9178
9179 /* ensure the target directory exists */
9180 if (targetCapabilities & MediumFormatCapabilities_File)
9181 {
9182 HRESULT rc = VirtualBox::i_ensureFilePathExists(targetLocation,
9183 !(task.mVariant & MediumVariant_NoCreateDir) /* fCreate */);
9184 if (FAILED(rc))
9185 throw rc;
9186 }
9187
9188 try
9189 {
9190 vrc = VDCopy(hdd,
9191 VD_LAST_IMAGE,
9192 hdd,
9193 targetFormat.c_str(),
9194 targetLocation.c_str(),
9195 true /* fMoveByRename */,
9196 0 /* cbSize */,
9197 VD_IMAGE_FLAGS_NONE,
9198 targetId.raw(),
9199 VD_OPEN_FLAGS_NORMAL,
9200 NULL /* pVDIfsOperation */,
9201 NULL,
9202 NULL);
9203 if (RT_FAILURE(vrc))
9204 throw setError(VBOX_E_FILE_ERROR,
9205 tr("Could not move medium '%s'%s"),
9206 targetLocation.c_str(), i_vdError(vrc).c_str());
9207 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
9208 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE);
9209 unsigned uImageFlags;
9210 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
9211 if (RT_SUCCESS(vrc))
9212 variant = (MediumVariant_T)uImageFlags;
9213
9214 /*
9215 * set current location, because VDCopy\VDCopyEx doesn't do it.
9216 * also reset moving flag
9217 */
9218 i_resetMoveOperationData();
9219 m->strLocationFull = targetLocation;
9220
9221 }
9222 catch (HRESULT aRC) { rcOut = aRC; }
9223
9224 }
9225 catch (HRESULT aRC) { rcOut = aRC; }
9226
9227 VDDestroy(hdd);
9228 }
9229 catch (HRESULT aRC) { rcOut = aRC; }
9230
9231 ErrorInfoKeeper eik;
9232 MultiResult mrc(rcOut);
9233
9234 // now, at the end of this task (always asynchronous), save the settings
9235 if (SUCCEEDED(mrc))
9236 {
9237 // save the settings
9238 i_markRegistriesModified();
9239 /* collect multiple errors */
9240 eik.restore();
9241 m->pVirtualBox->i_saveModifiedRegistries();
9242 eik.fetch();
9243 }
9244
9245 /* Everything is explicitly unlocked when the task exits,
9246 * as the task destruction also destroys the source chain. */
9247
9248 task.mpMediumLockList->Clear();
9249
9250 return mrc;
9251}
9252
9253/**
9254 * Implementation code for the "delete" task.
9255 *
9256 * This task always gets started from Medium::deleteStorage() and can run
9257 * synchronously or asynchronously depending on the "wait" parameter passed to
9258 * that function.
9259 *
9260 * @param task
9261 * @return
9262 */
9263HRESULT Medium::i_taskDeleteHandler(Medium::DeleteTask &task)
9264{
9265 NOREF(task);
9266 HRESULT rc = S_OK;
9267
9268 try
9269 {
9270 /* The lock is also used as a signal from the task initiator (which
9271 * releases it only after RTThreadCreate()) that we can start the job */
9272 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
9273
9274 PVDISK hdd;
9275 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
9276 ComAssertRCThrow(vrc, E_FAIL);
9277
9278 Utf8Str format(m->strFormat);
9279 Utf8Str location(m->strLocationFull);
9280
9281 /* unlock before the potentially lengthy operation */
9282 Assert(m->state == MediumState_Deleting);
9283 thisLock.release();
9284
9285 try
9286 {
9287 vrc = VDOpen(hdd,
9288 format.c_str(),
9289 location.c_str(),
9290 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO | m->uOpenFlagsDef,
9291 m->vdImageIfaces);
9292 if (RT_SUCCESS(vrc))
9293 vrc = VDClose(hdd, true /* fDelete */);
9294
9295 if (RT_FAILURE(vrc))
9296 throw setError(VBOX_E_FILE_ERROR,
9297 tr("Could not delete the medium storage unit '%s'%s"),
9298 location.c_str(), i_vdError(vrc).c_str());
9299
9300 }
9301 catch (HRESULT aRC) { rc = aRC; }
9302
9303 VDDestroy(hdd);
9304 }
9305 catch (HRESULT aRC) { rc = aRC; }
9306
9307 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
9308
9309 /* go to the NotCreated state even on failure since the storage
9310 * may have been already partially deleted and cannot be used any
9311 * more. One will be able to manually re-open the storage if really
9312 * needed to re-register it. */
9313 m->state = MediumState_NotCreated;
9314
9315 /* Reset UUID to prevent Create* from reusing it again */
9316 unconst(m->id).clear();
9317
9318 return rc;
9319}
9320
9321/**
9322 * Implementation code for the "reset" task.
9323 *
9324 * This always gets started asynchronously from Medium::Reset().
9325 *
9326 * @param task
9327 * @return
9328 */
9329HRESULT Medium::i_taskResetHandler(Medium::ResetTask &task)
9330{
9331 HRESULT rc = S_OK;
9332
9333 uint64_t size = 0, logicalSize = 0;
9334 MediumVariant_T variant = MediumVariant_Standard;
9335
9336 try
9337 {
9338 /* The lock is also used as a signal from the task initiator (which
9339 * releases it only after RTThreadCreate()) that we can start the job */
9340 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
9341
9342 /// @todo Below we use a pair of delete/create operations to reset
9343 /// the diff contents but the most efficient way will of course be
9344 /// to add a VDResetDiff() API call
9345
9346 PVDISK hdd;
9347 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
9348 ComAssertRCThrow(vrc, E_FAIL);
9349
9350 Guid id = m->id;
9351 Utf8Str format(m->strFormat);
9352 Utf8Str location(m->strLocationFull);
9353
9354 Medium *pParent = m->pParent;
9355 Guid parentId = pParent->m->id;
9356 Utf8Str parentFormat(pParent->m->strFormat);
9357 Utf8Str parentLocation(pParent->m->strLocationFull);
9358
9359 Assert(m->state == MediumState_LockedWrite);
9360
9361 /* unlock before the potentially lengthy operation */
9362 thisLock.release();
9363
9364 try
9365 {
9366 /* Open all media in the target chain but the last. */
9367 MediumLockList::Base::const_iterator targetListBegin =
9368 task.mpMediumLockList->GetBegin();
9369 MediumLockList::Base::const_iterator targetListEnd =
9370 task.mpMediumLockList->GetEnd();
9371 for (MediumLockList::Base::const_iterator it = targetListBegin;
9372 it != targetListEnd;
9373 ++it)
9374 {
9375 const MediumLock &mediumLock = *it;
9376 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
9377
9378 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
9379
9380 /* sanity check, "this" is checked above */
9381 Assert( pMedium == this
9382 || pMedium->m->state == MediumState_LockedRead);
9383
9384 /* Open all media in appropriate mode. */
9385 vrc = VDOpen(hdd,
9386 pMedium->m->strFormat.c_str(),
9387 pMedium->m->strLocationFull.c_str(),
9388 VD_OPEN_FLAGS_READONLY | m->uOpenFlagsDef,
9389 pMedium->m->vdImageIfaces);
9390 if (RT_FAILURE(vrc))
9391 throw setError(VBOX_E_FILE_ERROR,
9392 tr("Could not open the medium storage unit '%s'%s"),
9393 pMedium->m->strLocationFull.c_str(),
9394 i_vdError(vrc).c_str());
9395
9396 /* Done when we hit the media which should be reset */
9397 if (pMedium == this)
9398 break;
9399 }
9400
9401 /* first, delete the storage unit */
9402 vrc = VDClose(hdd, true /* fDelete */);
9403 if (RT_FAILURE(vrc))
9404 throw setError(VBOX_E_FILE_ERROR,
9405 tr("Could not delete the medium storage unit '%s'%s"),
9406 location.c_str(), i_vdError(vrc).c_str());
9407
9408 /* next, create it again */
9409 vrc = VDOpen(hdd,
9410 parentFormat.c_str(),
9411 parentLocation.c_str(),
9412 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO | m->uOpenFlagsDef,
9413 m->vdImageIfaces);
9414 if (RT_FAILURE(vrc))
9415 throw setError(VBOX_E_FILE_ERROR,
9416 tr("Could not open the medium storage unit '%s'%s"),
9417 parentLocation.c_str(), i_vdError(vrc).c_str());
9418
9419 vrc = VDCreateDiff(hdd,
9420 format.c_str(),
9421 location.c_str(),
9422 /// @todo use the same medium variant as before
9423 VD_IMAGE_FLAGS_NONE,
9424 NULL,
9425 id.raw(),
9426 parentId.raw(),
9427 VD_OPEN_FLAGS_NORMAL,
9428 m->vdImageIfaces,
9429 task.mVDOperationIfaces);
9430 if (RT_FAILURE(vrc))
9431 {
9432 if (vrc == VERR_VD_INVALID_TYPE)
9433 throw setError(VBOX_E_FILE_ERROR,
9434 tr("Parameters for creating the differencing medium storage unit '%s' are invalid%s"),
9435 location.c_str(), i_vdError(vrc).c_str());
9436 else
9437 throw setError(VBOX_E_FILE_ERROR,
9438 tr("Could not create the differencing medium storage unit '%s'%s"),
9439 location.c_str(), i_vdError(vrc).c_str());
9440 }
9441
9442 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
9443 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE);
9444 unsigned uImageFlags;
9445 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
9446 if (RT_SUCCESS(vrc))
9447 variant = (MediumVariant_T)uImageFlags;
9448 }
9449 catch (HRESULT aRC) { rc = aRC; }
9450
9451 VDDestroy(hdd);
9452 }
9453 catch (HRESULT aRC) { rc = aRC; }
9454
9455 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
9456
9457 m->size = size;
9458 m->logicalSize = logicalSize;
9459 m->variant = variant;
9460
9461 /* Everything is explicitly unlocked when the task exits,
9462 * as the task destruction also destroys the media chain. */
9463
9464 return rc;
9465}
9466
9467/**
9468 * Implementation code for the "compact" task.
9469 *
9470 * @param task
9471 * @return
9472 */
9473HRESULT Medium::i_taskCompactHandler(Medium::CompactTask &task)
9474{
9475 HRESULT rc = S_OK;
9476
9477 /* Lock all in {parent,child} order. The lock is also used as a
9478 * signal from the task initiator (which releases it only after
9479 * RTThreadCreate()) that we can start the job. */
9480 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
9481
9482 try
9483 {
9484 PVDISK hdd;
9485 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
9486 ComAssertRCThrow(vrc, E_FAIL);
9487
9488 try
9489 {
9490 /* Open all media in the chain. */
9491 MediumLockList::Base::const_iterator mediumListBegin =
9492 task.mpMediumLockList->GetBegin();
9493 MediumLockList::Base::const_iterator mediumListEnd =
9494 task.mpMediumLockList->GetEnd();
9495 MediumLockList::Base::const_iterator mediumListLast =
9496 mediumListEnd;
9497 --mediumListLast;
9498 for (MediumLockList::Base::const_iterator it = mediumListBegin;
9499 it != mediumListEnd;
9500 ++it)
9501 {
9502 const MediumLock &mediumLock = *it;
9503 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
9504 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
9505
9506 /* sanity check */
9507 if (it == mediumListLast)
9508 Assert(pMedium->m->state == MediumState_LockedWrite);
9509 else
9510 Assert(pMedium->m->state == MediumState_LockedRead);
9511
9512 /* Open all media but last in read-only mode. Do not handle
9513 * shareable media, as compaction and sharing are mutually
9514 * exclusive. */
9515 vrc = VDOpen(hdd,
9516 pMedium->m->strFormat.c_str(),
9517 pMedium->m->strLocationFull.c_str(),
9518 m->uOpenFlagsDef | (it == mediumListLast ? VD_OPEN_FLAGS_NORMAL : VD_OPEN_FLAGS_READONLY),
9519 pMedium->m->vdImageIfaces);
9520 if (RT_FAILURE(vrc))
9521 throw setError(VBOX_E_FILE_ERROR,
9522 tr("Could not open the medium storage unit '%s'%s"),
9523 pMedium->m->strLocationFull.c_str(),
9524 i_vdError(vrc).c_str());
9525 }
9526
9527 Assert(m->state == MediumState_LockedWrite);
9528
9529 Utf8Str location(m->strLocationFull);
9530
9531 /* unlock before the potentially lengthy operation */
9532 thisLock.release();
9533
9534 vrc = VDCompact(hdd, VD_LAST_IMAGE, task.mVDOperationIfaces);
9535 if (RT_FAILURE(vrc))
9536 {
9537 if (vrc == VERR_NOT_SUPPORTED)
9538 throw setError(VBOX_E_NOT_SUPPORTED,
9539 tr("Compacting is not yet supported for medium '%s'"),
9540 location.c_str());
9541 else if (vrc == VERR_NOT_IMPLEMENTED)
9542 throw setError(E_NOTIMPL,
9543 tr("Compacting is not implemented, medium '%s'"),
9544 location.c_str());
9545 else
9546 throw setError(VBOX_E_FILE_ERROR,
9547 tr("Could not compact medium '%s'%s"),
9548 location.c_str(),
9549 i_vdError(vrc).c_str());
9550 }
9551 }
9552 catch (HRESULT aRC) { rc = aRC; }
9553
9554 VDDestroy(hdd);
9555 }
9556 catch (HRESULT aRC) { rc = aRC; }
9557
9558 /* Everything is explicitly unlocked when the task exits,
9559 * as the task destruction also destroys the media chain. */
9560
9561 return rc;
9562}
9563
9564/**
9565 * Implementation code for the "resize" task.
9566 *
9567 * @param task
9568 * @return
9569 */
9570HRESULT Medium::i_taskResizeHandler(Medium::ResizeTask &task)
9571{
9572 HRESULT rc = S_OK;
9573
9574 uint64_t size = 0, logicalSize = 0;
9575
9576 try
9577 {
9578 /* The lock is also used as a signal from the task initiator (which
9579 * releases it only after RTThreadCreate()) that we can start the job */
9580 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
9581
9582 PVDISK hdd;
9583 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
9584 ComAssertRCThrow(vrc, E_FAIL);
9585
9586 try
9587 {
9588 /* Open all media in the chain. */
9589 MediumLockList::Base::const_iterator mediumListBegin =
9590 task.mpMediumLockList->GetBegin();
9591 MediumLockList::Base::const_iterator mediumListEnd =
9592 task.mpMediumLockList->GetEnd();
9593 MediumLockList::Base::const_iterator mediumListLast =
9594 mediumListEnd;
9595 --mediumListLast;
9596 for (MediumLockList::Base::const_iterator it = mediumListBegin;
9597 it != mediumListEnd;
9598 ++it)
9599 {
9600 const MediumLock &mediumLock = *it;
9601 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
9602 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
9603
9604 /* sanity check */
9605 if (it == mediumListLast)
9606 Assert(pMedium->m->state == MediumState_LockedWrite);
9607 else
9608 Assert(pMedium->m->state == MediumState_LockedRead);
9609
9610 /* Open all media but last in read-only mode. Do not handle
9611 * shareable media, as compaction and sharing are mutually
9612 * exclusive. */
9613 vrc = VDOpen(hdd,
9614 pMedium->m->strFormat.c_str(),
9615 pMedium->m->strLocationFull.c_str(),
9616 m->uOpenFlagsDef | (it == mediumListLast ? VD_OPEN_FLAGS_NORMAL : VD_OPEN_FLAGS_READONLY),
9617 pMedium->m->vdImageIfaces);
9618 if (RT_FAILURE(vrc))
9619 throw setError(VBOX_E_FILE_ERROR,
9620 tr("Could not open the medium storage unit '%s'%s"),
9621 pMedium->m->strLocationFull.c_str(),
9622 i_vdError(vrc).c_str());
9623 }
9624
9625 Assert(m->state == MediumState_LockedWrite);
9626
9627 Utf8Str location(m->strLocationFull);
9628
9629 /* unlock before the potentially lengthy operation */
9630 thisLock.release();
9631
9632 VDGEOMETRY geo = {0, 0, 0}; /* auto */
9633 vrc = VDResize(hdd, task.mSize, &geo, &geo, task.mVDOperationIfaces);
9634 if (RT_FAILURE(vrc))
9635 {
9636 if (vrc == VERR_NOT_SUPPORTED)
9637 throw setError(VBOX_E_NOT_SUPPORTED,
9638 tr("Resizing to new size %llu is not yet supported for medium '%s'"),
9639 task.mSize, location.c_str());
9640 else if (vrc == VERR_NOT_IMPLEMENTED)
9641 throw setError(E_NOTIMPL,
9642 tr("Resiting is not implemented, medium '%s'"),
9643 location.c_str());
9644 else
9645 throw setError(VBOX_E_FILE_ERROR,
9646 tr("Could not resize medium '%s'%s"),
9647 location.c_str(),
9648 i_vdError(vrc).c_str());
9649 }
9650 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
9651 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE);
9652 }
9653 catch (HRESULT aRC) { rc = aRC; }
9654
9655 VDDestroy(hdd);
9656 }
9657 catch (HRESULT aRC) { rc = aRC; }
9658
9659 if (SUCCEEDED(rc))
9660 {
9661 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
9662 m->size = size;
9663 m->logicalSize = logicalSize;
9664 }
9665
9666 /* Everything is explicitly unlocked when the task exits,
9667 * as the task destruction also destroys the media chain. */
9668
9669 return rc;
9670}
9671
9672/**
9673 * Implementation code for the "export" task.
9674 *
9675 * This only gets started from Medium::exportFile() and always runs
9676 * asynchronously. It doesn't touch anything configuration related, so
9677 * we never save the VirtualBox.xml file here.
9678 *
9679 * @param task
9680 * @return
9681 */
9682HRESULT Medium::i_taskExportHandler(Medium::ExportTask &task)
9683{
9684 HRESULT rc = S_OK;
9685
9686 try
9687 {
9688 /* Lock all in {parent,child} order. The lock is also used as a
9689 * signal from the task initiator (which releases it only after
9690 * RTThreadCreate()) that we can start the job. */
9691 ComObjPtr<Medium> pBase = i_getBase();
9692 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
9693
9694 PVDISK hdd;
9695 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
9696 ComAssertRCThrow(vrc, E_FAIL);
9697
9698 try
9699 {
9700 settings::StringsMap::iterator itKeyStore = pBase->m->mapProperties.find("CRYPT/KeyStore");
9701 if (itKeyStore != pBase->m->mapProperties.end())
9702 {
9703 settings::StringsMap::iterator itKeyId = pBase->m->mapProperties.find("CRYPT/KeyId");
9704
9705#ifdef VBOX_WITH_EXTPACK
9706 ExtPackManager *pExtPackManager = m->pVirtualBox->i_getExtPackManager();
9707 if (pExtPackManager->i_isExtPackUsable(ORACLE_PUEL_EXTPACK_NAME))
9708 {
9709 /* Load the plugin */
9710 Utf8Str strPlugin;
9711 rc = pExtPackManager->i_getLibraryPathForExtPack(g_szVDPlugin, ORACLE_PUEL_EXTPACK_NAME, &strPlugin);
9712 if (SUCCEEDED(rc))
9713 {
9714 vrc = VDPluginLoadFromFilename(strPlugin.c_str());
9715 if (RT_FAILURE(vrc))
9716 throw setError(VBOX_E_NOT_SUPPORTED,
9717 tr("Retrieving encryption settings of the image failed because the encryption plugin could not be loaded (%s)"),
9718 i_vdError(vrc).c_str());
9719 }
9720 else
9721 throw setError(VBOX_E_NOT_SUPPORTED,
9722 tr("Encryption is not supported because the extension pack '%s' is missing the encryption plugin (old extension pack installed?)"),
9723 ORACLE_PUEL_EXTPACK_NAME);
9724 }
9725 else
9726 throw setError(VBOX_E_NOT_SUPPORTED,
9727 tr("Encryption is not supported because the extension pack '%s' is missing"),
9728 ORACLE_PUEL_EXTPACK_NAME);
9729#else
9730 throw setError(VBOX_E_NOT_SUPPORTED,
9731 tr("Encryption is not supported because extension pack support is not built in"));
9732#endif
9733
9734 if (itKeyId == pBase->m->mapProperties.end())
9735 throw setError(VBOX_E_INVALID_OBJECT_STATE,
9736 tr("Image '%s' is configured for encryption but doesn't has a key identifier set"),
9737 pBase->m->strLocationFull.c_str());
9738
9739 /* Find the proper secret key in the key store. */
9740 if (!task.m_pSecretKeyStore)
9741 throw setError(VBOX_E_INVALID_OBJECT_STATE,
9742 tr("Image '%s' is configured for encryption but there is no key store to retrieve the password from"),
9743 pBase->m->strLocationFull.c_str());
9744
9745 SecretKey *pKey = NULL;
9746 vrc = task.m_pSecretKeyStore->retainSecretKey(itKeyId->second, &pKey);
9747 if (RT_FAILURE(vrc))
9748 throw setError(VBOX_E_INVALID_OBJECT_STATE,
9749 tr("Failed to retrieve the secret key with ID \"%s\" from the store (%Rrc)"),
9750 itKeyId->second.c_str(), vrc);
9751
9752 Medium::CryptoFilterSettings CryptoSettingsRead;
9753 i_taskEncryptSettingsSetup(&CryptoSettingsRead, NULL, itKeyStore->second.c_str(), (const char *)pKey->getKeyBuffer(),
9754 false /* fCreateKeyStore */);
9755 vrc = VDFilterAdd(hdd, "CRYPT", VD_FILTER_FLAGS_READ, CryptoSettingsRead.vdFilterIfaces);
9756 if (vrc == VERR_VD_PASSWORD_INCORRECT)
9757 {
9758 task.m_pSecretKeyStore->releaseSecretKey(itKeyId->second);
9759 throw setError(VBOX_E_PASSWORD_INCORRECT,
9760 tr("The password to decrypt the image is incorrect"));
9761 }
9762 else if (RT_FAILURE(vrc))
9763 {
9764 task.m_pSecretKeyStore->releaseSecretKey(itKeyId->second);
9765 throw setError(VBOX_E_INVALID_OBJECT_STATE,
9766 tr("Failed to load the decryption filter: %s"),
9767 i_vdError(vrc).c_str());
9768 }
9769
9770 task.m_pSecretKeyStore->releaseSecretKey(itKeyId->second);
9771 }
9772
9773 /* Open all media in the source chain. */
9774 MediumLockList::Base::const_iterator sourceListBegin =
9775 task.mpSourceMediumLockList->GetBegin();
9776 MediumLockList::Base::const_iterator sourceListEnd =
9777 task.mpSourceMediumLockList->GetEnd();
9778 for (MediumLockList::Base::const_iterator it = sourceListBegin;
9779 it != sourceListEnd;
9780 ++it)
9781 {
9782 const MediumLock &mediumLock = *it;
9783 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
9784 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
9785
9786 /* sanity check */
9787 Assert(pMedium->m->state == MediumState_LockedRead);
9788
9789 /* Open all media in read-only mode. */
9790 vrc = VDOpen(hdd,
9791 pMedium->m->strFormat.c_str(),
9792 pMedium->m->strLocationFull.c_str(),
9793 VD_OPEN_FLAGS_READONLY | m->uOpenFlagsDef,
9794 pMedium->m->vdImageIfaces);
9795 if (RT_FAILURE(vrc))
9796 throw setError(VBOX_E_FILE_ERROR,
9797 tr("Could not open the medium storage unit '%s'%s"),
9798 pMedium->m->strLocationFull.c_str(),
9799 i_vdError(vrc).c_str());
9800 }
9801
9802 Utf8Str targetFormat(task.mFormat->i_getId());
9803 Utf8Str targetLocation(task.mFilename);
9804 uint64_t capabilities = task.mFormat->i_getCapabilities();
9805
9806 Assert(m->state == MediumState_LockedRead);
9807
9808 /* unlock before the potentially lengthy operation */
9809 thisLock.release();
9810
9811 /* ensure the target directory exists */
9812 if (capabilities & MediumFormatCapabilities_File)
9813 {
9814 rc = VirtualBox::i_ensureFilePathExists(targetLocation,
9815 !(task.mVariant & MediumVariant_NoCreateDir) /* fCreate */);
9816 if (FAILED(rc))
9817 throw rc;
9818 }
9819
9820 PVDISK targetHdd;
9821 vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &targetHdd);
9822 ComAssertRCThrow(vrc, E_FAIL);
9823
9824 try
9825 {
9826 vrc = VDCopy(hdd,
9827 VD_LAST_IMAGE,
9828 targetHdd,
9829 targetFormat.c_str(),
9830 targetLocation.c_str(),
9831 false /* fMoveByRename */,
9832 0 /* cbSize */,
9833 task.mVariant & ~MediumVariant_NoCreateDir,
9834 NULL /* pDstUuid */,
9835 VD_OPEN_FLAGS_NORMAL | VD_OPEN_FLAGS_SEQUENTIAL,
9836 NULL /* pVDIfsOperation */,
9837 task.mVDImageIfaces,
9838 task.mVDOperationIfaces);
9839 if (RT_FAILURE(vrc))
9840 throw setError(VBOX_E_FILE_ERROR,
9841 tr("Could not create the exported medium '%s'%s"),
9842 targetLocation.c_str(), i_vdError(vrc).c_str());
9843 }
9844 catch (HRESULT aRC) { rc = aRC; }
9845
9846 VDDestroy(targetHdd);
9847 }
9848 catch (HRESULT aRC) { rc = aRC; }
9849
9850 VDDestroy(hdd);
9851 }
9852 catch (HRESULT aRC) { rc = aRC; }
9853
9854 /* Everything is explicitly unlocked when the task exits,
9855 * as the task destruction also destroys the source chain. */
9856
9857 /* Make sure the source chain is released early, otherwise it can
9858 * lead to deadlocks with concurrent IAppliance activities. */
9859 task.mpSourceMediumLockList->Clear();
9860
9861 return rc;
9862}
9863
9864/**
9865 * Implementation code for the "import" task.
9866 *
9867 * This only gets started from Medium::importFile() and always runs
9868 * asynchronously. It potentially touches the media registry, so we
9869 * always save the VirtualBox.xml file when we're done here.
9870 *
9871 * @param task
9872 * @return
9873 */
9874HRESULT Medium::i_taskImportHandler(Medium::ImportTask &task)
9875{
9876 /** @todo r=klaus The code below needs to be double checked with regard
9877 * to lock order violations, it probably causes lock order issues related
9878 * to the AutoCaller usage. */
9879 HRESULT rcTmp = S_OK;
9880
9881 const ComObjPtr<Medium> &pParent = task.mParent;
9882
9883 bool fCreatingTarget = false;
9884
9885 uint64_t size = 0, logicalSize = 0;
9886 MediumVariant_T variant = MediumVariant_Standard;
9887 bool fGenerateUuid = false;
9888
9889 try
9890 {
9891 if (!pParent.isNull())
9892 if (pParent->i_getDepth() >= SETTINGS_MEDIUM_DEPTH_MAX)
9893 {
9894 AutoReadLock plock(pParent COMMA_LOCKVAL_SRC_POS);
9895 throw setError(VBOX_E_INVALID_OBJECT_STATE,
9896 tr("Cannot import image for medium '%s', because it exceeds the medium tree depth limit. Please merge some images which you no longer need"),
9897 pParent->m->strLocationFull.c_str());
9898 }
9899
9900 /* Lock all in {parent,child} order. The lock is also used as a
9901 * signal from the task initiator (which releases it only after
9902 * RTThreadCreate()) that we can start the job. */
9903 AutoMultiWriteLock2 thisLock(this, pParent COMMA_LOCKVAL_SRC_POS);
9904
9905 fCreatingTarget = m->state == MediumState_Creating;
9906
9907 /* The object may request a specific UUID (through a special form of
9908 * the setLocation() argument). Otherwise we have to generate it */
9909 Guid targetId = m->id;
9910
9911 fGenerateUuid = targetId.isZero();
9912 if (fGenerateUuid)
9913 {
9914 targetId.create();
9915 /* VirtualBox::i_registerMedium() will need UUID */
9916 unconst(m->id) = targetId;
9917 }
9918
9919
9920 PVDISK hdd;
9921 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
9922 ComAssertRCThrow(vrc, E_FAIL);
9923
9924 try
9925 {
9926 /* Open source medium. */
9927 vrc = VDOpen(hdd,
9928 task.mFormat->i_getId().c_str(),
9929 task.mFilename.c_str(),
9930 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_SEQUENTIAL | m->uOpenFlagsDef,
9931 task.mVDImageIfaces);
9932 if (RT_FAILURE(vrc))
9933 throw setError(VBOX_E_FILE_ERROR,
9934 tr("Could not open the medium storage unit '%s'%s"),
9935 task.mFilename.c_str(),
9936 i_vdError(vrc).c_str());
9937
9938 Utf8Str targetFormat(m->strFormat);
9939 Utf8Str targetLocation(m->strLocationFull);
9940 uint64_t capabilities = task.mFormat->i_getCapabilities();
9941
9942 Assert( m->state == MediumState_Creating
9943 || m->state == MediumState_LockedWrite);
9944 Assert( pParent.isNull()
9945 || pParent->m->state == MediumState_LockedRead);
9946
9947 /* unlock before the potentially lengthy operation */
9948 thisLock.release();
9949
9950 /* ensure the target directory exists */
9951 if (capabilities & MediumFormatCapabilities_File)
9952 {
9953 HRESULT rc = VirtualBox::i_ensureFilePathExists(targetLocation,
9954 !(task.mVariant & MediumVariant_NoCreateDir) /* fCreate */);
9955 if (FAILED(rc))
9956 throw rc;
9957 }
9958
9959 PVDISK targetHdd;
9960 vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &targetHdd);
9961 ComAssertRCThrow(vrc, E_FAIL);
9962
9963 try
9964 {
9965 /* Open all media in the target chain. */
9966 MediumLockList::Base::const_iterator targetListBegin =
9967 task.mpTargetMediumLockList->GetBegin();
9968 MediumLockList::Base::const_iterator targetListEnd =
9969 task.mpTargetMediumLockList->GetEnd();
9970 for (MediumLockList::Base::const_iterator it = targetListBegin;
9971 it != targetListEnd;
9972 ++it)
9973 {
9974 const MediumLock &mediumLock = *it;
9975 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
9976
9977 /* If the target medium is not created yet there's no
9978 * reason to open it. */
9979 if (pMedium == this && fCreatingTarget)
9980 continue;
9981
9982 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
9983
9984 /* sanity check */
9985 Assert( pMedium->m->state == MediumState_LockedRead
9986 || pMedium->m->state == MediumState_LockedWrite);
9987
9988 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
9989 if (pMedium->m->state != MediumState_LockedWrite)
9990 uOpenFlags = VD_OPEN_FLAGS_READONLY;
9991 if (pMedium->m->type == MediumType_Shareable)
9992 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
9993
9994 /* Open all media in appropriate mode. */
9995 vrc = VDOpen(targetHdd,
9996 pMedium->m->strFormat.c_str(),
9997 pMedium->m->strLocationFull.c_str(),
9998 uOpenFlags | m->uOpenFlagsDef,
9999 pMedium->m->vdImageIfaces);
10000 if (RT_FAILURE(vrc))
10001 throw setError(VBOX_E_FILE_ERROR,
10002 tr("Could not open the medium storage unit '%s'%s"),
10003 pMedium->m->strLocationFull.c_str(),
10004 i_vdError(vrc).c_str());
10005 }
10006
10007 vrc = VDCopy(hdd,
10008 VD_LAST_IMAGE,
10009 targetHdd,
10010 targetFormat.c_str(),
10011 (fCreatingTarget) ? targetLocation.c_str() : (char *)NULL,
10012 false /* fMoveByRename */,
10013 0 /* cbSize */,
10014 task.mVariant & ~MediumVariant_NoCreateDir,
10015 targetId.raw(),
10016 VD_OPEN_FLAGS_NORMAL,
10017 NULL /* pVDIfsOperation */,
10018 m->vdImageIfaces,
10019 task.mVDOperationIfaces);
10020 if (RT_FAILURE(vrc))
10021 throw setError(VBOX_E_FILE_ERROR,
10022 tr("Could not create the imported medium '%s'%s"),
10023 targetLocation.c_str(), i_vdError(vrc).c_str());
10024
10025 size = VDGetFileSize(targetHdd, VD_LAST_IMAGE);
10026 logicalSize = VDGetSize(targetHdd, VD_LAST_IMAGE);
10027 unsigned uImageFlags;
10028 vrc = VDGetImageFlags(targetHdd, 0, &uImageFlags);
10029 if (RT_SUCCESS(vrc))
10030 variant = (MediumVariant_T)uImageFlags;
10031 }
10032 catch (HRESULT aRC) { rcTmp = aRC; }
10033
10034 VDDestroy(targetHdd);
10035 }
10036 catch (HRESULT aRC) { rcTmp = aRC; }
10037
10038 VDDestroy(hdd);
10039 }
10040 catch (HRESULT aRC) { rcTmp = aRC; }
10041
10042 ErrorInfoKeeper eik;
10043 MultiResult mrc(rcTmp);
10044
10045 /* Only do the parent changes for newly created media. */
10046 if (SUCCEEDED(mrc) && fCreatingTarget)
10047 {
10048 /* we set m->pParent & children() */
10049 AutoWriteLock treeLock(m->pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
10050
10051 Assert(m->pParent.isNull());
10052
10053 if (pParent)
10054 {
10055 /* Associate the imported medium with the parent and deassociate
10056 * from VirtualBox. Depth check above. */
10057 i_setParent(pParent);
10058
10059 /* register with mVirtualBox as the last step and move to
10060 * Created state only on success (leaving an orphan file is
10061 * better than breaking media registry consistency) */
10062 eik.restore();
10063 ComObjPtr<Medium> pMedium;
10064 mrc = pParent->m->pVirtualBox->i_registerMedium(this, &pMedium,
10065 treeLock);
10066 Assert(this == pMedium);
10067 eik.fetch();
10068
10069 if (FAILED(mrc))
10070 /* break parent association on failure to register */
10071 this->i_deparent(); // removes target from parent
10072 }
10073 else
10074 {
10075 /* just register */
10076 eik.restore();
10077 ComObjPtr<Medium> pMedium;
10078 mrc = m->pVirtualBox->i_registerMedium(this, &pMedium, treeLock);
10079 Assert(this == pMedium);
10080 eik.fetch();
10081 }
10082 }
10083
10084 if (fCreatingTarget)
10085 {
10086 AutoWriteLock mLock(this COMMA_LOCKVAL_SRC_POS);
10087
10088 if (SUCCEEDED(mrc))
10089 {
10090 m->state = MediumState_Created;
10091
10092 m->size = size;
10093 m->logicalSize = logicalSize;
10094 m->variant = variant;
10095 }
10096 else
10097 {
10098 /* back to NotCreated on failure */
10099 m->state = MediumState_NotCreated;
10100
10101 /* reset UUID to prevent it from being reused next time */
10102 if (fGenerateUuid)
10103 unconst(m->id).clear();
10104 }
10105 }
10106
10107 // now, at the end of this task (always asynchronous), save the settings
10108 {
10109 // save the settings
10110 i_markRegistriesModified();
10111 /* collect multiple errors */
10112 eik.restore();
10113 m->pVirtualBox->i_saveModifiedRegistries();
10114 eik.fetch();
10115 }
10116
10117 /* Everything is explicitly unlocked when the task exits,
10118 * as the task destruction also destroys the target chain. */
10119
10120 /* Make sure the target chain is released early, otherwise it can
10121 * lead to deadlocks with concurrent IAppliance activities. */
10122 task.mpTargetMediumLockList->Clear();
10123
10124 return mrc;
10125}
10126
10127/**
10128 * Sets up the encryption settings for a filter.
10129 */
10130void Medium::i_taskEncryptSettingsSetup(CryptoFilterSettings *pSettings, const char *pszCipher,
10131 const char *pszKeyStore, const char *pszPassword,
10132 bool fCreateKeyStore)
10133{
10134 pSettings->pszCipher = pszCipher;
10135 pSettings->pszPassword = pszPassword;
10136 pSettings->pszKeyStoreLoad = pszKeyStore;
10137 pSettings->fCreateKeyStore = fCreateKeyStore;
10138 pSettings->pbDek = NULL;
10139 pSettings->cbDek = 0;
10140 pSettings->vdFilterIfaces = NULL;
10141
10142 pSettings->vdIfCfg.pfnAreKeysValid = i_vdCryptoConfigAreKeysValid;
10143 pSettings->vdIfCfg.pfnQuerySize = i_vdCryptoConfigQuerySize;
10144 pSettings->vdIfCfg.pfnQuery = i_vdCryptoConfigQuery;
10145 pSettings->vdIfCfg.pfnQueryBytes = NULL;
10146
10147 pSettings->vdIfCrypto.pfnKeyRetain = i_vdCryptoKeyRetain;
10148 pSettings->vdIfCrypto.pfnKeyRelease = i_vdCryptoKeyRelease;
10149 pSettings->vdIfCrypto.pfnKeyStorePasswordRetain = i_vdCryptoKeyStorePasswordRetain;
10150 pSettings->vdIfCrypto.pfnKeyStorePasswordRelease = i_vdCryptoKeyStorePasswordRelease;
10151 pSettings->vdIfCrypto.pfnKeyStoreSave = i_vdCryptoKeyStoreSave;
10152 pSettings->vdIfCrypto.pfnKeyStoreReturnParameters = i_vdCryptoKeyStoreReturnParameters;
10153
10154 int vrc = VDInterfaceAdd(&pSettings->vdIfCfg.Core,
10155 "Medium::vdInterfaceCfgCrypto",
10156 VDINTERFACETYPE_CONFIG, pSettings,
10157 sizeof(VDINTERFACECONFIG), &pSettings->vdFilterIfaces);
10158 AssertRC(vrc);
10159
10160 vrc = VDInterfaceAdd(&pSettings->vdIfCrypto.Core,
10161 "Medium::vdInterfaceCrypto",
10162 VDINTERFACETYPE_CRYPTO, pSettings,
10163 sizeof(VDINTERFACECRYPTO), &pSettings->vdFilterIfaces);
10164 AssertRC(vrc);
10165}
10166
10167/**
10168 * Implementation code for the "encrypt" task.
10169 *
10170 * @param task
10171 * @return
10172 */
10173HRESULT Medium::i_taskEncryptHandler(Medium::EncryptTask &task)
10174{
10175# ifndef VBOX_WITH_EXTPACK
10176 RT_NOREF(task);
10177# endif
10178 HRESULT rc = S_OK;
10179
10180 /* Lock all in {parent,child} order. The lock is also used as a
10181 * signal from the task initiator (which releases it only after
10182 * RTThreadCreate()) that we can start the job. */
10183 ComObjPtr<Medium> pBase = i_getBase();
10184 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
10185
10186 try
10187 {
10188# ifdef VBOX_WITH_EXTPACK
10189 ExtPackManager *pExtPackManager = m->pVirtualBox->i_getExtPackManager();
10190 if (pExtPackManager->i_isExtPackUsable(ORACLE_PUEL_EXTPACK_NAME))
10191 {
10192 /* Load the plugin */
10193 Utf8Str strPlugin;
10194 rc = pExtPackManager->i_getLibraryPathForExtPack(g_szVDPlugin, ORACLE_PUEL_EXTPACK_NAME, &strPlugin);
10195 if (SUCCEEDED(rc))
10196 {
10197 int vrc = VDPluginLoadFromFilename(strPlugin.c_str());
10198 if (RT_FAILURE(vrc))
10199 throw setError(VBOX_E_NOT_SUPPORTED,
10200 tr("Encrypting the image failed because the encryption plugin could not be loaded (%s)"),
10201 i_vdError(vrc).c_str());
10202 }
10203 else
10204 throw setError(VBOX_E_NOT_SUPPORTED,
10205 tr("Encryption is not supported because the extension pack '%s' is missing the encryption plugin (old extension pack installed?)"),
10206 ORACLE_PUEL_EXTPACK_NAME);
10207 }
10208 else
10209 throw setError(VBOX_E_NOT_SUPPORTED,
10210 tr("Encryption is not supported because the extension pack '%s' is missing"),
10211 ORACLE_PUEL_EXTPACK_NAME);
10212
10213 PVDISK pDisk = NULL;
10214 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &pDisk);
10215 ComAssertRCThrow(vrc, E_FAIL);
10216
10217 Medium::CryptoFilterSettings CryptoSettingsRead;
10218 Medium::CryptoFilterSettings CryptoSettingsWrite;
10219
10220 void *pvBuf = NULL;
10221 const char *pszPasswordNew = NULL;
10222 try
10223 {
10224 /* Set up disk encryption filters. */
10225 if (task.mstrCurrentPassword.isEmpty())
10226 {
10227 /*
10228 * Query whether the medium property indicating that encryption is
10229 * configured is existing.
10230 */
10231 settings::StringsMap::iterator it = pBase->m->mapProperties.find("CRYPT/KeyStore");
10232 if (it != pBase->m->mapProperties.end())
10233 throw setError(VBOX_E_PASSWORD_INCORRECT,
10234 tr("The password given for the encrypted image is incorrect"));
10235 }
10236 else
10237 {
10238 settings::StringsMap::iterator it = pBase->m->mapProperties.find("CRYPT/KeyStore");
10239 if (it == pBase->m->mapProperties.end())
10240 throw setError(VBOX_E_INVALID_OBJECT_STATE,
10241 tr("The image is not configured for encryption"));
10242
10243 i_taskEncryptSettingsSetup(&CryptoSettingsRead, NULL, it->second.c_str(), task.mstrCurrentPassword.c_str(),
10244 false /* fCreateKeyStore */);
10245 vrc = VDFilterAdd(pDisk, "CRYPT", VD_FILTER_FLAGS_READ, CryptoSettingsRead.vdFilterIfaces);
10246 if (vrc == VERR_VD_PASSWORD_INCORRECT)
10247 throw setError(VBOX_E_PASSWORD_INCORRECT,
10248 tr("The password to decrypt the image is incorrect"));
10249 else if (RT_FAILURE(vrc))
10250 throw setError(VBOX_E_INVALID_OBJECT_STATE,
10251 tr("Failed to load the decryption filter: %s"),
10252 i_vdError(vrc).c_str());
10253 }
10254
10255 if (task.mstrCipher.isNotEmpty())
10256 {
10257 if ( task.mstrNewPassword.isEmpty()
10258 && task.mstrNewPasswordId.isEmpty()
10259 && task.mstrCurrentPassword.isNotEmpty())
10260 {
10261 /* An empty password and password ID will default to the current password. */
10262 pszPasswordNew = task.mstrCurrentPassword.c_str();
10263 }
10264 else if (task.mstrNewPassword.isEmpty())
10265 throw setError(VBOX_E_OBJECT_NOT_FOUND,
10266 tr("A password must be given for the image encryption"));
10267 else if (task.mstrNewPasswordId.isEmpty())
10268 throw setError(VBOX_E_INVALID_OBJECT_STATE,
10269 tr("A valid identifier for the password must be given"));
10270 else
10271 pszPasswordNew = task.mstrNewPassword.c_str();
10272
10273 i_taskEncryptSettingsSetup(&CryptoSettingsWrite, task.mstrCipher.c_str(), NULL,
10274 pszPasswordNew, true /* fCreateKeyStore */);
10275 vrc = VDFilterAdd(pDisk, "CRYPT", VD_FILTER_FLAGS_WRITE, CryptoSettingsWrite.vdFilterIfaces);
10276 if (RT_FAILURE(vrc))
10277 throw setError(VBOX_E_INVALID_OBJECT_STATE,
10278 tr("Failed to load the encryption filter: %s"),
10279 i_vdError(vrc).c_str());
10280 }
10281 else if (task.mstrNewPasswordId.isNotEmpty() || task.mstrNewPassword.isNotEmpty())
10282 throw setError(VBOX_E_INVALID_OBJECT_STATE,
10283 tr("The password and password identifier must be empty if the output should be unencrypted"));
10284
10285 /* Open all media in the chain. */
10286 MediumLockList::Base::const_iterator mediumListBegin =
10287 task.mpMediumLockList->GetBegin();
10288 MediumLockList::Base::const_iterator mediumListEnd =
10289 task.mpMediumLockList->GetEnd();
10290 MediumLockList::Base::const_iterator mediumListLast =
10291 mediumListEnd;
10292 --mediumListLast;
10293 for (MediumLockList::Base::const_iterator it = mediumListBegin;
10294 it != mediumListEnd;
10295 ++it)
10296 {
10297 const MediumLock &mediumLock = *it;
10298 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
10299 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
10300
10301 Assert(pMedium->m->state == MediumState_LockedWrite);
10302
10303 /* Open all media but last in read-only mode. Do not handle
10304 * shareable media, as compaction and sharing are mutually
10305 * exclusive. */
10306 vrc = VDOpen(pDisk,
10307 pMedium->m->strFormat.c_str(),
10308 pMedium->m->strLocationFull.c_str(),
10309 m->uOpenFlagsDef | (it == mediumListLast ? VD_OPEN_FLAGS_NORMAL : VD_OPEN_FLAGS_READONLY),
10310 pMedium->m->vdImageIfaces);
10311 if (RT_FAILURE(vrc))
10312 throw setError(VBOX_E_FILE_ERROR,
10313 tr("Could not open the medium storage unit '%s'%s"),
10314 pMedium->m->strLocationFull.c_str(),
10315 i_vdError(vrc).c_str());
10316 }
10317
10318 Assert(m->state == MediumState_LockedWrite);
10319
10320 Utf8Str location(m->strLocationFull);
10321
10322 /* unlock before the potentially lengthy operation */
10323 thisLock.release();
10324
10325 vrc = VDPrepareWithFilters(pDisk, task.mVDOperationIfaces);
10326 if (RT_FAILURE(vrc))
10327 throw setError(VBOX_E_FILE_ERROR,
10328 tr("Could not prepare disk images for encryption (%Rrc): %s"),
10329 vrc, i_vdError(vrc).c_str());
10330
10331 thisLock.acquire();
10332 /* If everything went well set the new key store. */
10333 settings::StringsMap::iterator it = pBase->m->mapProperties.find("CRYPT/KeyStore");
10334 if (it != pBase->m->mapProperties.end())
10335 pBase->m->mapProperties.erase(it);
10336
10337 /* Delete KeyId if encryption is removed or the password did change. */
10338 if ( task.mstrNewPasswordId.isNotEmpty()
10339 || task.mstrCipher.isEmpty())
10340 {
10341 it = pBase->m->mapProperties.find("CRYPT/KeyId");
10342 if (it != pBase->m->mapProperties.end())
10343 pBase->m->mapProperties.erase(it);
10344 }
10345
10346 if (CryptoSettingsWrite.pszKeyStore)
10347 {
10348 pBase->m->mapProperties["CRYPT/KeyStore"] = Utf8Str(CryptoSettingsWrite.pszKeyStore);
10349 if (task.mstrNewPasswordId.isNotEmpty())
10350 pBase->m->mapProperties["CRYPT/KeyId"] = task.mstrNewPasswordId;
10351 }
10352
10353 if (CryptoSettingsRead.pszCipherReturned)
10354 RTStrFree(CryptoSettingsRead.pszCipherReturned);
10355
10356 if (CryptoSettingsWrite.pszCipherReturned)
10357 RTStrFree(CryptoSettingsWrite.pszCipherReturned);
10358
10359 thisLock.release();
10360 pBase->i_markRegistriesModified();
10361 m->pVirtualBox->i_saveModifiedRegistries();
10362 }
10363 catch (HRESULT aRC) { rc = aRC; }
10364
10365 if (pvBuf)
10366 RTMemFree(pvBuf);
10367
10368 VDDestroy(pDisk);
10369# else
10370 throw setError(VBOX_E_NOT_SUPPORTED,
10371 tr("Encryption is not supported because extension pack support is not built in"));
10372# endif
10373 }
10374 catch (HRESULT aRC) { rc = aRC; }
10375
10376 /* Everything is explicitly unlocked when the task exits,
10377 * as the task destruction also destroys the media chain. */
10378
10379 return rc;
10380}
10381
10382/* vi: set tabstop=4 shiftwidth=4 expandtab: */
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