VirtualBox

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

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

Main/MediumImpl: bugref:8344: use RTPathStartsWithRoot() to ensure that the medium is fully qualified. Less strict than calling RTPathAbs() but sufficient. Cosmetic changes.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 361.5 KB
Line 
1/* $Id: MediumImpl.cpp 67239 2017-06-02 13:37:59Z 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 sourcePath = i_getLocationFull();
3071 Utf8Str sourceFName = 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 destPath(aLocation);
3083 Utf8Str destFName(destPath);
3084 destFName.stripPath();
3085
3086 Utf8Str suffix(destFName);
3087 suffix.stripSuffix();
3088
3089 if (suffix.equals(destFName) && !destFName.isEmpty())
3090 {
3091 /*
3092 * The target path has no filename: Either "/path/to/new/location" or
3093 * just "newname" (no trailing backslash or there is no filename with
3094 * extension(suffix)).
3095 */
3096 if (destPath.equals(destFName))
3097 {
3098 /* new path contains only "newname", no path, no extension */
3099 destFName.append(RTPathSuffix(sourceFName.c_str()));
3100 destPath = destFName;
3101 }
3102 else
3103 {
3104 /* new path looks like "/path/to/new/location" */
3105 destFName.setNull();
3106 destPath.append(RTPATH_SLASH);
3107 }
3108 }
3109
3110 if (destFName.isEmpty())
3111 {
3112 /* No target name */
3113 destPath.append(sourceFName);
3114 }
3115 else
3116 {
3117 if (destPath.equals(destFName))
3118 {
3119 /*
3120 * The target path contains of only a filename without a directory.
3121 * Move the medium within the source directory to the new name
3122 * (actually rename operation).
3123 * Scratches sourcePath!
3124 */
3125 destPath = sourcePath.stripFilename().append(RTPATH_SLASH).append(destFName);
3126 }
3127 suffix = i_getFormat();
3128 if (suffix.compare("RAW", Utf8Str::CaseInsensitive) == 0)
3129 {
3130 if (i_getDeviceType() == DeviceType_DVD)
3131 suffix = "iso";
3132 else
3133 {
3134 rc = setError(VERR_NOT_A_FILE,
3135 tr("Medium '%s' has RAW type. \"Move\" operation isn't supported for this type."),
3136 i_getLocationFull().c_str());
3137 throw rc;
3138 }
3139 }
3140 /* Set the target extension like on the source. Any conversions are prohibited */
3141 suffix.toLower();
3142 destPath.stripSuffix().append('.').append(suffix);
3143 }
3144
3145 if (!i_isMediumFormatFile())
3146 {
3147 rc = setError(VERR_NOT_A_FILE,
3148 tr("Medium '%s' isn't a file object. \"Move\" operation isn't supported."),
3149 i_getLocationFull().c_str());
3150 throw rc;
3151 }
3152 /* Path must be absolute */
3153 if (!RTPathStartsWithRoot(destPath.c_str()))
3154 {
3155 rc = setError(VBOX_E_FILE_ERROR,
3156 tr("The given path '%s' is not fully qualified"),
3157 destPath.c_str());
3158 throw rc;
3159 }
3160 /* Check path for a new file object */
3161 rc = VirtualBox::i_ensureFilePathExists(destPath, true);
3162 if (FAILED(rc))
3163 throw rc;
3164
3165 /* Set needed variables for "moving" procedure. It'll be used later in separate thread task */
3166 rc = i_preparationForMoving(destPath);
3167 if (FAILED(rc))
3168 {
3169 rc = setError(VERR_NO_CHANGE,
3170 tr("Medium '%s' is already in the correct location"),
3171 i_getLocationFull().c_str());
3172 throw rc;
3173 }
3174 }
3175
3176 /* Check VMs which have this medium attached to*/
3177 std::vector<com::Guid> aMachineIds;
3178 rc = getMachineIds(aMachineIds);
3179 std::vector<com::Guid>::const_iterator currMachineID = aMachineIds.begin();
3180 std::vector<com::Guid>::const_iterator lastMachineID = aMachineIds.end();
3181
3182 while (currMachineID != lastMachineID)
3183 {
3184 Guid id(*currMachineID);
3185 ComObjPtr<Machine> aMachine;
3186
3187 alock.release();
3188 rc = m->pVirtualBox->i_findMachine(id, false, true, &aMachine);
3189 alock.acquire();
3190
3191 if (SUCCEEDED(rc))
3192 {
3193 ComObjPtr<SessionMachine> sm;
3194 ComPtr<IInternalSessionControl> ctl;
3195
3196 alock.release();
3197 bool ses = aMachine->i_isSessionOpenVM(sm, &ctl);
3198 alock.acquire();
3199
3200 if (ses)
3201 {
3202 rc = setError(VERR_VM_UNEXPECTED_VM_STATE,
3203 tr("At least the VM '%s' to whom this medium '%s' attached has currently an opened session. Stop all VMs before relocating this medium"),
3204 id.toString().c_str(),
3205 i_getLocationFull().c_str());
3206 throw rc;
3207 }
3208 }
3209 ++currMachineID;
3210 }
3211
3212 /* Build the source lock list. */
3213 MediumLockList *pMediumLockList(new MediumLockList());
3214 alock.release();
3215 rc = i_createMediumLockList(true /* fFailIfInaccessible */,
3216 this /* pToLockWrite */,
3217 true /* fMediumLockWriteAll */,
3218 NULL,
3219 *pMediumLockList);
3220 alock.acquire();
3221 if (FAILED(rc))
3222 {
3223 delete pMediumLockList;
3224 throw setError(rc,
3225 tr("Failed to create medium lock list for '%s'"),
3226 i_getLocationFull().c_str());
3227 }
3228 alock.release();
3229 rc = pMediumLockList->Lock();
3230 alock.acquire();
3231 if (FAILED(rc))
3232 {
3233 delete pMediumLockList;
3234 throw setError(rc,
3235 tr("Failed to lock media '%s'"),
3236 i_getLocationFull().c_str());
3237 }
3238
3239 pProgress.createObject();
3240 rc = pProgress->init(m->pVirtualBox,
3241 static_cast <IMedium *>(this),
3242 BstrFmt(tr("Moving medium '%s'"), m->strLocationFull.c_str()).raw(),
3243 TRUE /* aCancelable */);
3244
3245 /* Do the disk moving. */
3246 if (SUCCEEDED(rc))
3247 {
3248 ULONG mediumVariantFlags = i_getVariant();
3249
3250 /* setup task object to carry out the operation asynchronously */
3251 pTask = new Medium::MoveTask(this, pProgress,
3252 (MediumVariant_T)mediumVariantFlags,
3253 pMediumLockList);
3254 rc = pTask->rc();
3255 AssertComRC(rc);
3256 if (FAILED(rc))
3257 throw rc;
3258 }
3259
3260 }
3261 catch (HRESULT aRC) { rc = aRC; }
3262
3263 if (SUCCEEDED(rc))
3264 {
3265 rc = pTask->createThread();
3266
3267 if (SUCCEEDED(rc))
3268 pProgress.queryInterfaceTo(aProgress.asOutParam());
3269 }
3270 else
3271 {
3272 if (pTask)
3273 delete pTask;
3274 }
3275
3276 return rc;
3277}
3278
3279HRESULT Medium::compact(ComPtr<IProgress> &aProgress)
3280{
3281 HRESULT rc = S_OK;
3282 ComObjPtr<Progress> pProgress;
3283 Medium::Task *pTask = NULL;
3284
3285 try
3286 {
3287 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3288
3289 /* Build the medium lock list. */
3290 MediumLockList *pMediumLockList(new MediumLockList());
3291 alock.release();
3292 rc = i_createMediumLockList(true /* fFailIfInaccessible */ ,
3293 this /* pToLockWrite */,
3294 false /* fMediumLockWriteAll */,
3295 NULL,
3296 *pMediumLockList);
3297 alock.acquire();
3298 if (FAILED(rc))
3299 {
3300 delete pMediumLockList;
3301 throw rc;
3302 }
3303
3304 alock.release();
3305 rc = pMediumLockList->Lock();
3306 alock.acquire();
3307 if (FAILED(rc))
3308 {
3309 delete pMediumLockList;
3310 throw setError(rc,
3311 tr("Failed to lock media when compacting '%s'"),
3312 i_getLocationFull().c_str());
3313 }
3314
3315 pProgress.createObject();
3316 rc = pProgress->init(m->pVirtualBox,
3317 static_cast <IMedium *>(this),
3318 BstrFmt(tr("Compacting medium '%s'"), m->strLocationFull.c_str()).raw(),
3319 TRUE /* aCancelable */);
3320 if (FAILED(rc))
3321 {
3322 delete pMediumLockList;
3323 throw rc;
3324 }
3325
3326 /* setup task object to carry out the operation asynchronously */
3327 pTask = new Medium::CompactTask(this, pProgress, pMediumLockList);
3328 rc = pTask->rc();
3329 AssertComRC(rc);
3330 if (FAILED(rc))
3331 throw rc;
3332 }
3333 catch (HRESULT aRC) { rc = aRC; }
3334
3335 if (SUCCEEDED(rc))
3336 {
3337 rc = pTask->createThread();
3338
3339 if (SUCCEEDED(rc))
3340 pProgress.queryInterfaceTo(aProgress.asOutParam());
3341 }
3342 else if (pTask != NULL)
3343 delete pTask;
3344
3345 return rc;
3346}
3347
3348HRESULT Medium::resize(LONG64 aLogicalSize,
3349 ComPtr<IProgress> &aProgress)
3350{
3351 HRESULT rc = S_OK;
3352 ComObjPtr<Progress> pProgress;
3353 Medium::Task *pTask = NULL;
3354
3355 try
3356 {
3357 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3358
3359 /* Build the medium lock list. */
3360 MediumLockList *pMediumLockList(new MediumLockList());
3361 alock.release();
3362 rc = i_createMediumLockList(true /* fFailIfInaccessible */ ,
3363 this /* pToLockWrite */,
3364 false /* fMediumLockWriteAll */,
3365 NULL,
3366 *pMediumLockList);
3367 alock.acquire();
3368 if (FAILED(rc))
3369 {
3370 delete pMediumLockList;
3371 throw rc;
3372 }
3373
3374 alock.release();
3375 rc = pMediumLockList->Lock();
3376 alock.acquire();
3377 if (FAILED(rc))
3378 {
3379 delete pMediumLockList;
3380 throw setError(rc,
3381 tr("Failed to lock media when compacting '%s'"),
3382 i_getLocationFull().c_str());
3383 }
3384
3385 pProgress.createObject();
3386 rc = pProgress->init(m->pVirtualBox,
3387 static_cast <IMedium *>(this),
3388 BstrFmt(tr("Compacting medium '%s'"), m->strLocationFull.c_str()).raw(),
3389 TRUE /* aCancelable */);
3390 if (FAILED(rc))
3391 {
3392 delete pMediumLockList;
3393 throw rc;
3394 }
3395
3396 /* setup task object to carry out the operation asynchronously */
3397 pTask = new Medium::ResizeTask(this, aLogicalSize, pProgress, pMediumLockList);
3398 rc = pTask->rc();
3399 AssertComRC(rc);
3400 if (FAILED(rc))
3401 throw rc;
3402 }
3403 catch (HRESULT aRC) { rc = aRC; }
3404
3405 if (SUCCEEDED(rc))
3406 {
3407 rc = pTask->createThread();
3408
3409 if (SUCCEEDED(rc))
3410 pProgress.queryInterfaceTo(aProgress.asOutParam());
3411 }
3412 else if (pTask != NULL)
3413 delete pTask;
3414
3415 return rc;
3416}
3417
3418HRESULT Medium::reset(AutoCaller &autoCaller, ComPtr<IProgress> &aProgress)
3419{
3420 HRESULT rc = S_OK;
3421 ComObjPtr<Progress> pProgress;
3422 Medium::Task *pTask = NULL;
3423
3424 try
3425 {
3426 autoCaller.release();
3427
3428 /* It is possible that some previous/concurrent uninit has already
3429 * cleared the pVirtualBox reference, see #uninit(). */
3430 ComObjPtr<VirtualBox> pVirtualBox(m->pVirtualBox);
3431
3432 /* canClose() needs the tree lock */
3433 AutoMultiWriteLock2 multilock(!pVirtualBox.isNull() ? &pVirtualBox->i_getMediaTreeLockHandle() : NULL,
3434 this->lockHandle()
3435 COMMA_LOCKVAL_SRC_POS);
3436
3437 autoCaller.add();
3438 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3439
3440 LogFlowThisFunc(("ENTER for medium %s\n", m->strLocationFull.c_str()));
3441
3442 if (m->pParent.isNull())
3443 throw setError(VBOX_E_NOT_SUPPORTED,
3444 tr("Medium type of '%s' is not differencing"),
3445 m->strLocationFull.c_str());
3446
3447 rc = i_canClose();
3448 if (FAILED(rc))
3449 throw rc;
3450
3451 /* Build the medium lock list. */
3452 MediumLockList *pMediumLockList(new MediumLockList());
3453 multilock.release();
3454 rc = i_createMediumLockList(true /* fFailIfInaccessible */,
3455 this /* pToLockWrite */,
3456 false /* fMediumLockWriteAll */,
3457 NULL,
3458 *pMediumLockList);
3459 multilock.acquire();
3460 if (FAILED(rc))
3461 {
3462 delete pMediumLockList;
3463 throw rc;
3464 }
3465
3466 multilock.release();
3467 rc = pMediumLockList->Lock();
3468 multilock.acquire();
3469 if (FAILED(rc))
3470 {
3471 delete pMediumLockList;
3472 throw setError(rc,
3473 tr("Failed to lock media when resetting '%s'"),
3474 i_getLocationFull().c_str());
3475 }
3476
3477 pProgress.createObject();
3478 rc = pProgress->init(m->pVirtualBox,
3479 static_cast<IMedium*>(this),
3480 BstrFmt(tr("Resetting differencing medium '%s'"), m->strLocationFull.c_str()).raw(),
3481 FALSE /* aCancelable */);
3482 if (FAILED(rc))
3483 throw rc;
3484
3485 /* setup task object to carry out the operation asynchronously */
3486 pTask = new Medium::ResetTask(this, pProgress, pMediumLockList);
3487 rc = pTask->rc();
3488 AssertComRC(rc);
3489 if (FAILED(rc))
3490 throw rc;
3491 }
3492 catch (HRESULT aRC) { rc = aRC; }
3493
3494 if (SUCCEEDED(rc))
3495 {
3496 rc = pTask->createThread();
3497
3498 if (SUCCEEDED(rc))
3499 pProgress.queryInterfaceTo(aProgress.asOutParam());
3500 }
3501 else if (pTask != NULL)
3502 delete pTask;
3503
3504 LogFlowThisFunc(("LEAVE, rc=%Rhrc\n", rc));
3505
3506 return rc;
3507}
3508
3509HRESULT Medium::changeEncryption(const com::Utf8Str &aCurrentPassword, const com::Utf8Str &aCipher,
3510 const com::Utf8Str &aNewPassword, const com::Utf8Str &aNewPasswordId,
3511 ComPtr<IProgress> &aProgress)
3512{
3513 HRESULT rc = S_OK;
3514 ComObjPtr<Progress> pProgress;
3515 Medium::Task *pTask = NULL;
3516
3517 try
3518 {
3519 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3520
3521 DeviceType_T devType = i_getDeviceType();
3522 /* Cannot encrypt DVD or floppy images so far. */
3523 if ( devType == DeviceType_DVD
3524 || devType == DeviceType_Floppy)
3525 return setError(VBOX_E_INVALID_OBJECT_STATE,
3526 tr("Cannot encrypt DVD or Floppy medium '%s'"),
3527 m->strLocationFull.c_str());
3528
3529 /* Cannot encrypt media which are attached to more than one virtual machine. */
3530 if (m->backRefs.size() > 1)
3531 return setError(VBOX_E_INVALID_OBJECT_STATE,
3532 tr("Cannot encrypt medium '%s' because it is attached to %d virtual machines"),
3533 m->strLocationFull.c_str(), m->backRefs.size());
3534
3535 if (i_getChildren().size() != 0)
3536 return setError(VBOX_E_INVALID_OBJECT_STATE,
3537 tr("Cannot encrypt medium '%s' because it has %d children"),
3538 m->strLocationFull.c_str(), i_getChildren().size());
3539
3540 /* Build the medium lock list. */
3541 MediumLockList *pMediumLockList(new MediumLockList());
3542 alock.release();
3543 rc = i_createMediumLockList(true /* fFailIfInaccessible */ ,
3544 this /* pToLockWrite */,
3545 true /* fMediumLockAllWrite */,
3546 NULL,
3547 *pMediumLockList);
3548 alock.acquire();
3549 if (FAILED(rc))
3550 {
3551 delete pMediumLockList;
3552 throw rc;
3553 }
3554
3555 alock.release();
3556 rc = pMediumLockList->Lock();
3557 alock.acquire();
3558 if (FAILED(rc))
3559 {
3560 delete pMediumLockList;
3561 throw setError(rc,
3562 tr("Failed to lock media for encryption '%s'"),
3563 i_getLocationFull().c_str());
3564 }
3565
3566 /*
3567 * Check all media in the chain to not contain any branches or references to
3568 * other virtual machines, we support encrypting only a list of differencing media at the moment.
3569 */
3570 MediumLockList::Base::const_iterator mediumListBegin = pMediumLockList->GetBegin();
3571 MediumLockList::Base::const_iterator mediumListEnd = pMediumLockList->GetEnd();
3572 for (MediumLockList::Base::const_iterator it = mediumListBegin;
3573 it != mediumListEnd;
3574 ++it)
3575 {
3576 const MediumLock &mediumLock = *it;
3577 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
3578 AutoReadLock mediumReadLock(pMedium COMMA_LOCKVAL_SRC_POS);
3579
3580 Assert(pMedium->m->state == MediumState_LockedWrite);
3581
3582 if (pMedium->m->backRefs.size() > 1)
3583 {
3584 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3585 tr("Cannot encrypt medium '%s' because it is attached to %d virtual machines"),
3586 pMedium->m->strLocationFull.c_str(), pMedium->m->backRefs.size());
3587 break;
3588 }
3589 else if (pMedium->i_getChildren().size() > 1)
3590 {
3591 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3592 tr("Cannot encrypt medium '%s' because it has %d children"),
3593 pMedium->m->strLocationFull.c_str(), pMedium->i_getChildren().size());
3594 break;
3595 }
3596 }
3597
3598 if (FAILED(rc))
3599 {
3600 delete pMediumLockList;
3601 throw rc;
3602 }
3603
3604 const char *pszAction = "Encrypting";
3605 if ( aCurrentPassword.isNotEmpty()
3606 && aCipher.isEmpty())
3607 pszAction = "Decrypting";
3608
3609 pProgress.createObject();
3610 rc = pProgress->init(m->pVirtualBox,
3611 static_cast <IMedium *>(this),
3612 BstrFmt(tr("%s medium '%s'"), pszAction, m->strLocationFull.c_str()).raw(),
3613 TRUE /* aCancelable */);
3614 if (FAILED(rc))
3615 {
3616 delete pMediumLockList;
3617 throw rc;
3618 }
3619
3620 /* setup task object to carry out the operation asynchronously */
3621 pTask = new Medium::EncryptTask(this, aNewPassword, aCurrentPassword,
3622 aCipher, aNewPasswordId, pProgress, pMediumLockList);
3623 rc = pTask->rc();
3624 AssertComRC(rc);
3625 if (FAILED(rc))
3626 throw rc;
3627 }
3628 catch (HRESULT aRC) { rc = aRC; }
3629
3630 if (SUCCEEDED(rc))
3631 {
3632 rc = pTask->createThread();
3633
3634 if (SUCCEEDED(rc))
3635 pProgress.queryInterfaceTo(aProgress.asOutParam());
3636 }
3637 else if (pTask != NULL)
3638 delete pTask;
3639
3640 return rc;
3641}
3642
3643HRESULT Medium::getEncryptionSettings(com::Utf8Str &aCipher, com::Utf8Str &aPasswordId)
3644{
3645#ifndef VBOX_WITH_EXTPACK
3646 RT_NOREF(aCipher, aPasswordId);
3647#endif
3648 HRESULT rc = S_OK;
3649
3650 try
3651 {
3652 ComObjPtr<Medium> pBase = i_getBase();
3653 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3654
3655 /* Check whether encryption is configured for this medium. */
3656 settings::StringsMap::iterator it = pBase->m->mapProperties.find("CRYPT/KeyStore");
3657 if (it == pBase->m->mapProperties.end())
3658 throw VBOX_E_NOT_SUPPORTED;
3659
3660# ifdef VBOX_WITH_EXTPACK
3661 ExtPackManager *pExtPackManager = m->pVirtualBox->i_getExtPackManager();
3662 if (pExtPackManager->i_isExtPackUsable(ORACLE_PUEL_EXTPACK_NAME))
3663 {
3664 /* Load the plugin */
3665 Utf8Str strPlugin;
3666 rc = pExtPackManager->i_getLibraryPathForExtPack(g_szVDPlugin, ORACLE_PUEL_EXTPACK_NAME, &strPlugin);
3667 if (SUCCEEDED(rc))
3668 {
3669 int vrc = VDPluginLoadFromFilename(strPlugin.c_str());
3670 if (RT_FAILURE(vrc))
3671 throw setError(VBOX_E_NOT_SUPPORTED,
3672 tr("Retrieving encryption settings of the image failed because the encryption plugin could not be loaded (%s)"),
3673 i_vdError(vrc).c_str());
3674 }
3675 else
3676 throw setError(VBOX_E_NOT_SUPPORTED,
3677 tr("Encryption is not supported because the extension pack '%s' is missing the encryption plugin (old extension pack installed?)"),
3678 ORACLE_PUEL_EXTPACK_NAME);
3679 }
3680 else
3681 throw setError(VBOX_E_NOT_SUPPORTED,
3682 tr("Encryption is not supported because the extension pack '%s' is missing"),
3683 ORACLE_PUEL_EXTPACK_NAME);
3684
3685 PVDISK pDisk = NULL;
3686 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &pDisk);
3687 ComAssertRCThrow(vrc, E_FAIL);
3688
3689 Medium::CryptoFilterSettings CryptoSettings;
3690
3691 i_taskEncryptSettingsSetup(&CryptoSettings, NULL, it->second.c_str(), NULL, false /* fCreateKeyStore */);
3692 vrc = VDFilterAdd(pDisk, "CRYPT", VD_FILTER_FLAGS_READ | VD_FILTER_FLAGS_INFO, CryptoSettings.vdFilterIfaces);
3693 if (RT_FAILURE(vrc))
3694 throw setError(VBOX_E_INVALID_OBJECT_STATE,
3695 tr("Failed to load the encryption filter: %s"),
3696 i_vdError(vrc).c_str());
3697
3698 it = pBase->m->mapProperties.find("CRYPT/KeyId");
3699 if (it == pBase->m->mapProperties.end())
3700 throw setError(VBOX_E_INVALID_OBJECT_STATE,
3701 tr("Image is configured for encryption but doesn't has a KeyId set"));
3702
3703 aPasswordId = it->second.c_str();
3704 aCipher = CryptoSettings.pszCipherReturned;
3705 RTStrFree(CryptoSettings.pszCipherReturned);
3706
3707 VDDestroy(pDisk);
3708# else
3709 throw setError(VBOX_E_NOT_SUPPORTED,
3710 tr("Encryption is not supported because extension pack support is not built in"));
3711# endif
3712 }
3713 catch (HRESULT aRC) { rc = aRC; }
3714
3715 return rc;
3716}
3717
3718HRESULT Medium::checkEncryptionPassword(const com::Utf8Str &aPassword)
3719{
3720 HRESULT rc = S_OK;
3721
3722 try
3723 {
3724 ComObjPtr<Medium> pBase = i_getBase();
3725 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3726
3727 settings::StringsMap::iterator it = pBase->m->mapProperties.find("CRYPT/KeyStore");
3728 if (it == pBase->m->mapProperties.end())
3729 throw setError(VBOX_E_NOT_SUPPORTED,
3730 tr("The image is not configured for encryption"));
3731
3732 if (aPassword.isEmpty())
3733 throw setError(E_INVALIDARG,
3734 tr("The given password must not be empty"));
3735
3736# ifdef VBOX_WITH_EXTPACK
3737 ExtPackManager *pExtPackManager = m->pVirtualBox->i_getExtPackManager();
3738 if (pExtPackManager->i_isExtPackUsable(ORACLE_PUEL_EXTPACK_NAME))
3739 {
3740 /* Load the plugin */
3741 Utf8Str strPlugin;
3742 rc = pExtPackManager->i_getLibraryPathForExtPack(g_szVDPlugin, ORACLE_PUEL_EXTPACK_NAME, &strPlugin);
3743 if (SUCCEEDED(rc))
3744 {
3745 int vrc = VDPluginLoadFromFilename(strPlugin.c_str());
3746 if (RT_FAILURE(vrc))
3747 throw setError(VBOX_E_NOT_SUPPORTED,
3748 tr("Retrieving encryption settings of the image failed because the encryption plugin could not be loaded (%s)"),
3749 i_vdError(vrc).c_str());
3750 }
3751 else
3752 throw setError(VBOX_E_NOT_SUPPORTED,
3753 tr("Encryption is not supported because the extension pack '%s' is missing the encryption plugin (old extension pack installed?)"),
3754 ORACLE_PUEL_EXTPACK_NAME);
3755 }
3756 else
3757 throw setError(VBOX_E_NOT_SUPPORTED,
3758 tr("Encryption is not supported because the extension pack '%s' is missing"),
3759 ORACLE_PUEL_EXTPACK_NAME);
3760
3761 PVDISK pDisk = NULL;
3762 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &pDisk);
3763 ComAssertRCThrow(vrc, E_FAIL);
3764
3765 Medium::CryptoFilterSettings CryptoSettings;
3766
3767 i_taskEncryptSettingsSetup(&CryptoSettings, NULL, it->second.c_str(), aPassword.c_str(),
3768 false /* fCreateKeyStore */);
3769 vrc = VDFilterAdd(pDisk, "CRYPT", VD_FILTER_FLAGS_READ, CryptoSettings.vdFilterIfaces);
3770 if (vrc == VERR_VD_PASSWORD_INCORRECT)
3771 throw setError(VBOX_E_PASSWORD_INCORRECT,
3772 tr("The given password is incorrect"));
3773 else if (RT_FAILURE(vrc))
3774 throw setError(VBOX_E_INVALID_OBJECT_STATE,
3775 tr("Failed to load the encryption filter: %s"),
3776 i_vdError(vrc).c_str());
3777
3778 VDDestroy(pDisk);
3779# else
3780 throw setError(VBOX_E_NOT_SUPPORTED,
3781 tr("Encryption is not supported because extension pack support is not built in"));
3782# endif
3783 }
3784 catch (HRESULT aRC) { rc = aRC; }
3785
3786 return rc;
3787}
3788
3789////////////////////////////////////////////////////////////////////////////////
3790//
3791// Medium public internal methods
3792//
3793////////////////////////////////////////////////////////////////////////////////
3794
3795/**
3796 * Internal method to return the medium's parent medium. Must have caller + locking!
3797 * @return
3798 */
3799const ComObjPtr<Medium>& Medium::i_getParent() const
3800{
3801 return m->pParent;
3802}
3803
3804/**
3805 * Internal method to return the medium's list of child media. Must have caller + locking!
3806 * @return
3807 */
3808const MediaList& Medium::i_getChildren() const
3809{
3810 return m->llChildren;
3811}
3812
3813/**
3814 * Internal method to return the medium's GUID. Must have caller + locking!
3815 * @return
3816 */
3817const Guid& Medium::i_getId() const
3818{
3819 return m->id;
3820}
3821
3822/**
3823 * Internal method to return the medium's state. Must have caller + locking!
3824 * @return
3825 */
3826MediumState_T Medium::i_getState() const
3827{
3828 return m->state;
3829}
3830
3831/**
3832 * Internal method to return the medium's variant. Must have caller + locking!
3833 * @return
3834 */
3835MediumVariant_T Medium::i_getVariant() const
3836{
3837 return m->variant;
3838}
3839
3840/**
3841 * Internal method which returns true if this medium represents a host drive.
3842 * @return
3843 */
3844bool Medium::i_isHostDrive() const
3845{
3846 return m->hostDrive;
3847}
3848
3849/**
3850 * Internal method to return the medium's full location. Must have caller + locking!
3851 * @return
3852 */
3853const Utf8Str& Medium::i_getLocationFull() const
3854{
3855 return m->strLocationFull;
3856}
3857
3858/**
3859 * Internal method to return the medium's format string. Must have caller + locking!
3860 * @return
3861 */
3862const Utf8Str& Medium::i_getFormat() const
3863{
3864 return m->strFormat;
3865}
3866
3867/**
3868 * Internal method to return the medium's format object. Must have caller + locking!
3869 * @return
3870 */
3871const ComObjPtr<MediumFormat>& Medium::i_getMediumFormat() const
3872{
3873 return m->formatObj;
3874}
3875
3876/**
3877 * Internal method that returns true if the medium is represented by a file on the host disk
3878 * (and not iSCSI or something).
3879 * @return
3880 */
3881bool Medium::i_isMediumFormatFile() const
3882{
3883 if ( m->formatObj
3884 && (m->formatObj->i_getCapabilities() & MediumFormatCapabilities_File)
3885 )
3886 return true;
3887 return false;
3888}
3889
3890/**
3891 * Internal method to return the medium's size. Must have caller + locking!
3892 * @return
3893 */
3894uint64_t Medium::i_getSize() const
3895{
3896 return m->size;
3897}
3898
3899/**
3900 * Returns the medium device type. Must have caller + locking!
3901 * @return
3902 */
3903DeviceType_T Medium::i_getDeviceType() const
3904{
3905 return m->devType;
3906}
3907
3908/**
3909 * Returns the medium type. Must have caller + locking!
3910 * @return
3911 */
3912MediumType_T Medium::i_getType() const
3913{
3914 return m->type;
3915}
3916
3917/**
3918 * Returns a short version of the location attribute.
3919 *
3920 * @note Must be called from under this object's read or write lock.
3921 */
3922Utf8Str Medium::i_getName()
3923{
3924 Utf8Str name = RTPathFilename(m->strLocationFull.c_str());
3925 return name;
3926}
3927
3928/**
3929 * This adds the given UUID to the list of media registries in which this
3930 * medium should be registered. The UUID can either be a machine UUID,
3931 * to add a machine registry, or the global registry UUID as returned by
3932 * VirtualBox::getGlobalRegistryId().
3933 *
3934 * Note that for hard disks, this method does nothing if the medium is
3935 * already in another registry to avoid having hard disks in more than
3936 * one registry, which causes trouble with keeping diff images in sync.
3937 * See getFirstRegistryMachineId() for details.
3938 *
3939 * @param id
3940 * @return true if the registry was added; false if the given id was already on the list.
3941 */
3942bool Medium::i_addRegistry(const Guid& id)
3943{
3944 AutoCaller autoCaller(this);
3945 if (FAILED(autoCaller.rc()))
3946 return false;
3947 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3948
3949 bool fAdd = true;
3950
3951 // hard disks cannot be in more than one registry
3952 if ( m->devType == DeviceType_HardDisk
3953 && m->llRegistryIDs.size() > 0)
3954 fAdd = false;
3955
3956 // no need to add the UUID twice
3957 if (fAdd)
3958 {
3959 for (GuidList::const_iterator it = m->llRegistryIDs.begin();
3960 it != m->llRegistryIDs.end();
3961 ++it)
3962 {
3963 if ((*it) == id)
3964 {
3965 fAdd = false;
3966 break;
3967 }
3968 }
3969 }
3970
3971 if (fAdd)
3972 m->llRegistryIDs.push_back(id);
3973
3974 return fAdd;
3975}
3976
3977/**
3978 * This adds the given UUID to the list of media registries in which this
3979 * medium should be registered. The UUID can either be a machine UUID,
3980 * to add a machine registry, or the global registry UUID as returned by
3981 * VirtualBox::getGlobalRegistryId(). This recurses over all children.
3982 *
3983 * Note that for hard disks, this method does nothing if the medium is
3984 * already in another registry to avoid having hard disks in more than
3985 * one registry, which causes trouble with keeping diff images in sync.
3986 * See getFirstRegistryMachineId() for details.
3987 *
3988 * @note the caller must hold the media tree lock for reading.
3989 *
3990 * @param id
3991 * @return true if the registry was added; false if the given id was already on the list.
3992 */
3993bool Medium::i_addRegistryRecursive(const Guid &id)
3994{
3995 AutoCaller autoCaller(this);
3996 if (FAILED(autoCaller.rc()))
3997 return false;
3998
3999 bool fAdd = i_addRegistry(id);
4000
4001 // protected by the medium tree lock held by our original caller
4002 for (MediaList::const_iterator it = i_getChildren().begin();
4003 it != i_getChildren().end();
4004 ++it)
4005 {
4006 Medium *pChild = *it;
4007 fAdd |= pChild->i_addRegistryRecursive(id);
4008 }
4009
4010 return fAdd;
4011}
4012
4013/**
4014 * Removes the given UUID from the list of media registry UUIDs of this medium.
4015 *
4016 * @param id
4017 * @return true if the UUID was found or false if not.
4018 */
4019bool Medium::i_removeRegistry(const Guid &id)
4020{
4021 AutoCaller autoCaller(this);
4022 if (FAILED(autoCaller.rc()))
4023 return false;
4024 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4025
4026 bool fRemove = false;
4027
4028 /// @todo r=klaus eliminate this code, replace it by using find.
4029 for (GuidList::iterator it = m->llRegistryIDs.begin();
4030 it != m->llRegistryIDs.end();
4031 ++it)
4032 {
4033 if ((*it) == id)
4034 {
4035 // getting away with this as the iterator isn't used after
4036 m->llRegistryIDs.erase(it);
4037 fRemove = true;
4038 break;
4039 }
4040 }
4041
4042 return fRemove;
4043}
4044
4045/**
4046 * Removes the given UUID from the list of media registry UUIDs, for this
4047 * medium and all its children recursively.
4048 *
4049 * @note the caller must hold the media tree lock for reading.
4050 *
4051 * @param id
4052 * @return true if the UUID was found or false if not.
4053 */
4054bool Medium::i_removeRegistryRecursive(const Guid &id)
4055{
4056 AutoCaller autoCaller(this);
4057 if (FAILED(autoCaller.rc()))
4058 return false;
4059
4060 bool fRemove = i_removeRegistry(id);
4061
4062 // protected by the medium tree lock held by our original caller
4063 for (MediaList::const_iterator it = i_getChildren().begin();
4064 it != i_getChildren().end();
4065 ++it)
4066 {
4067 Medium *pChild = *it;
4068 fRemove |= pChild->i_removeRegistryRecursive(id);
4069 }
4070
4071 return fRemove;
4072}
4073
4074/**
4075 * Returns true if id is in the list of media registries for this medium.
4076 *
4077 * Must have caller + read locking!
4078 *
4079 * @param id
4080 * @return
4081 */
4082bool Medium::i_isInRegistry(const Guid &id)
4083{
4084 /// @todo r=klaus eliminate this code, replace it by using find.
4085 for (GuidList::const_iterator it = m->llRegistryIDs.begin();
4086 it != m->llRegistryIDs.end();
4087 ++it)
4088 {
4089 if (*it == id)
4090 return true;
4091 }
4092
4093 return false;
4094}
4095
4096/**
4097 * Internal method to return the medium's first registry machine (i.e. the machine in whose
4098 * machine XML this medium is listed).
4099 *
4100 * Every attached medium must now (4.0) reside in at least one media registry, which is identified
4101 * by a UUID. This is either a machine UUID if the machine is from 4.0 or newer, in which case
4102 * machines have their own media registries, or it is the pseudo-UUID of the VirtualBox
4103 * object if the machine is old and still needs the global registry in VirtualBox.xml.
4104 *
4105 * By definition, hard disks may only be in one media registry, in which all its children
4106 * will be stored as well. Otherwise we run into problems with having keep multiple registries
4107 * in sync. (This is the "cloned VM" case in which VM1 may link to the disks of VM2; in this
4108 * case, only VM2's registry is used for the disk in question.)
4109 *
4110 * If there is no medium registry, particularly if the medium has not been attached yet, this
4111 * does not modify uuid and returns false.
4112 *
4113 * ISOs and RAWs, by contrast, can be in more than one repository to make things easier for
4114 * the user.
4115 *
4116 * Must have caller + locking!
4117 *
4118 * @param uuid Receives first registry machine UUID, if available.
4119 * @return true if uuid was set.
4120 */
4121bool Medium::i_getFirstRegistryMachineId(Guid &uuid) const
4122{
4123 if (m->llRegistryIDs.size())
4124 {
4125 uuid = m->llRegistryIDs.front();
4126 return true;
4127 }
4128 return false;
4129}
4130
4131/**
4132 * Marks all the registries in which this medium is registered as modified.
4133 */
4134void Medium::i_markRegistriesModified()
4135{
4136 AutoCaller autoCaller(this);
4137 if (FAILED(autoCaller.rc())) return;
4138
4139 // Get local copy, as keeping the lock over VirtualBox::markRegistryModified
4140 // causes trouble with the lock order
4141 GuidList llRegistryIDs;
4142 {
4143 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4144 llRegistryIDs = m->llRegistryIDs;
4145 }
4146
4147 autoCaller.release();
4148
4149 /* Save the error information now, the implicit restore when this goes
4150 * out of scope will throw away spurious additional errors created below. */
4151 ErrorInfoKeeper eik;
4152 for (GuidList::const_iterator it = llRegistryIDs.begin();
4153 it != llRegistryIDs.end();
4154 ++it)
4155 {
4156 m->pVirtualBox->i_markRegistryModified(*it);
4157 }
4158}
4159
4160/**
4161 * Adds the given machine and optionally the snapshot to the list of the objects
4162 * this medium is attached to.
4163 *
4164 * @param aMachineId Machine ID.
4165 * @param aSnapshotId Snapshot ID; when non-empty, adds a snapshot attachment.
4166 */
4167HRESULT Medium::i_addBackReference(const Guid &aMachineId,
4168 const Guid &aSnapshotId /*= Guid::Empty*/)
4169{
4170 AssertReturn(aMachineId.isValid(), E_FAIL);
4171
4172 LogFlowThisFunc(("ENTER, aMachineId: {%RTuuid}, aSnapshotId: {%RTuuid}\n", aMachineId.raw(), aSnapshotId.raw()));
4173
4174 AutoCaller autoCaller(this);
4175 AssertComRCReturnRC(autoCaller.rc());
4176
4177 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4178
4179 switch (m->state)
4180 {
4181 case MediumState_Created:
4182 case MediumState_Inaccessible:
4183 case MediumState_LockedRead:
4184 case MediumState_LockedWrite:
4185 break;
4186
4187 default:
4188 return i_setStateError();
4189 }
4190
4191 if (m->numCreateDiffTasks > 0)
4192 return setError(VBOX_E_OBJECT_IN_USE,
4193 tr("Cannot attach medium '%s' {%RTuuid}: %u differencing child media are being created"),
4194 m->strLocationFull.c_str(),
4195 m->id.raw(),
4196 m->numCreateDiffTasks);
4197
4198 BackRefList::iterator it = std::find_if(m->backRefs.begin(),
4199 m->backRefs.end(),
4200 BackRef::EqualsTo(aMachineId));
4201 if (it == m->backRefs.end())
4202 {
4203 BackRef ref(aMachineId, aSnapshotId);
4204 m->backRefs.push_back(ref);
4205
4206 return S_OK;
4207 }
4208
4209 // if the caller has not supplied a snapshot ID, then we're attaching
4210 // to a machine a medium which represents the machine's current state,
4211 // so set the flag
4212
4213 if (aSnapshotId.isZero())
4214 {
4215 /* sanity: no duplicate attachments */
4216 if (it->fInCurState)
4217 return setError(VBOX_E_OBJECT_IN_USE,
4218 tr("Cannot attach medium '%s' {%RTuuid}: medium is already associated with the current state of machine uuid {%RTuuid}!"),
4219 m->strLocationFull.c_str(),
4220 m->id.raw(),
4221 aMachineId.raw());
4222 it->fInCurState = true;
4223
4224 return S_OK;
4225 }
4226
4227 // otherwise: a snapshot medium is being attached
4228
4229 /* sanity: no duplicate attachments */
4230 for (GuidList::const_iterator jt = it->llSnapshotIds.begin();
4231 jt != it->llSnapshotIds.end();
4232 ++jt)
4233 {
4234 const Guid &idOldSnapshot = *jt;
4235
4236 if (idOldSnapshot == aSnapshotId)
4237 {
4238#ifdef DEBUG
4239 i_dumpBackRefs();
4240#endif
4241 return setError(VBOX_E_OBJECT_IN_USE,
4242 tr("Cannot attach medium '%s' {%RTuuid} from snapshot '%RTuuid': medium is already in use by this snapshot!"),
4243 m->strLocationFull.c_str(),
4244 m->id.raw(),
4245 aSnapshotId.raw());
4246 }
4247 }
4248
4249 it->llSnapshotIds.push_back(aSnapshotId);
4250 // Do not touch fInCurState, as the image may be attached to the current
4251 // state *and* a snapshot, otherwise we lose the current state association!
4252
4253 LogFlowThisFuncLeave();
4254
4255 return S_OK;
4256}
4257
4258/**
4259 * Removes the given machine and optionally the snapshot from the list of the
4260 * objects this medium is attached to.
4261 *
4262 * @param aMachineId Machine ID.
4263 * @param aSnapshotId Snapshot ID; when non-empty, removes the snapshot
4264 * attachment.
4265 */
4266HRESULT Medium::i_removeBackReference(const Guid &aMachineId,
4267 const Guid &aSnapshotId /*= Guid::Empty*/)
4268{
4269 AssertReturn(aMachineId.isValid(), E_FAIL);
4270
4271 AutoCaller autoCaller(this);
4272 AssertComRCReturnRC(autoCaller.rc());
4273
4274 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4275
4276 BackRefList::iterator it =
4277 std::find_if(m->backRefs.begin(), m->backRefs.end(),
4278 BackRef::EqualsTo(aMachineId));
4279 AssertReturn(it != m->backRefs.end(), E_FAIL);
4280
4281 if (aSnapshotId.isZero())
4282 {
4283 /* remove the current state attachment */
4284 it->fInCurState = false;
4285 }
4286 else
4287 {
4288 /* remove the snapshot attachment */
4289 GuidList::iterator jt = std::find(it->llSnapshotIds.begin(),
4290 it->llSnapshotIds.end(),
4291 aSnapshotId);
4292
4293 AssertReturn(jt != it->llSnapshotIds.end(), E_FAIL);
4294 it->llSnapshotIds.erase(jt);
4295 }
4296
4297 /* if the backref becomes empty, remove it */
4298 if (it->fInCurState == false && it->llSnapshotIds.size() == 0)
4299 m->backRefs.erase(it);
4300
4301 return S_OK;
4302}
4303
4304/**
4305 * Internal method to return the medium's list of backrefs. Must have caller + locking!
4306 * @return
4307 */
4308const Guid* Medium::i_getFirstMachineBackrefId() const
4309{
4310 if (!m->backRefs.size())
4311 return NULL;
4312
4313 return &m->backRefs.front().machineId;
4314}
4315
4316/**
4317 * Internal method which returns a machine that either this medium or one of its children
4318 * is attached to. This is used for finding a replacement media registry when an existing
4319 * media registry is about to be deleted in VirtualBox::unregisterMachine().
4320 *
4321 * Must have caller + locking, *and* caller must hold the media tree lock!
4322 * @return
4323 */
4324const Guid* Medium::i_getAnyMachineBackref() const
4325{
4326 if (m->backRefs.size())
4327 return &m->backRefs.front().machineId;
4328
4329 for (MediaList::const_iterator it = i_getChildren().begin();
4330 it != i_getChildren().end();
4331 ++it)
4332 {
4333 Medium *pChild = *it;
4334 // recurse for this child
4335 const Guid* puuid;
4336 if ((puuid = pChild->i_getAnyMachineBackref()))
4337 return puuid;
4338 }
4339
4340 return NULL;
4341}
4342
4343const Guid* Medium::i_getFirstMachineBackrefSnapshotId() const
4344{
4345 if (!m->backRefs.size())
4346 return NULL;
4347
4348 const BackRef &ref = m->backRefs.front();
4349 if (ref.llSnapshotIds.empty())
4350 return NULL;
4351
4352 return &ref.llSnapshotIds.front();
4353}
4354
4355size_t Medium::i_getMachineBackRefCount() const
4356{
4357 return m->backRefs.size();
4358}
4359
4360#ifdef DEBUG
4361/**
4362 * Debugging helper that gets called after VirtualBox initialization that writes all
4363 * machine backreferences to the debug log.
4364 */
4365void Medium::i_dumpBackRefs()
4366{
4367 AutoCaller autoCaller(this);
4368 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4369
4370 LogFlowThisFunc(("Dumping backrefs for medium '%s':\n", m->strLocationFull.c_str()));
4371
4372 for (BackRefList::iterator it2 = m->backRefs.begin();
4373 it2 != m->backRefs.end();
4374 ++it2)
4375 {
4376 const BackRef &ref = *it2;
4377 LogFlowThisFunc((" Backref from machine {%RTuuid} (fInCurState: %d)\n", ref.machineId.raw(), ref.fInCurState));
4378
4379 for (GuidList::const_iterator jt2 = it2->llSnapshotIds.begin();
4380 jt2 != it2->llSnapshotIds.end();
4381 ++jt2)
4382 {
4383 const Guid &id = *jt2;
4384 LogFlowThisFunc((" Backref from snapshot {%RTuuid}\n", id.raw()));
4385 }
4386 }
4387}
4388#endif
4389
4390/**
4391 * Checks if the given change of \a aOldPath to \a aNewPath affects the location
4392 * of this media and updates it if necessary to reflect the new location.
4393 *
4394 * @param strOldPath Old path (full).
4395 * @param strNewPath New path (full).
4396 *
4397 * @note Locks this object for writing.
4398 */
4399HRESULT Medium::i_updatePath(const Utf8Str &strOldPath, const Utf8Str &strNewPath)
4400{
4401 AssertReturn(!strOldPath.isEmpty(), E_FAIL);
4402 AssertReturn(!strNewPath.isEmpty(), E_FAIL);
4403
4404 AutoCaller autoCaller(this);
4405 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4406
4407 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4408
4409 LogFlowThisFunc(("locationFull.before='%s'\n", m->strLocationFull.c_str()));
4410
4411 const char *pcszMediumPath = m->strLocationFull.c_str();
4412
4413 if (RTPathStartsWith(pcszMediumPath, strOldPath.c_str()))
4414 {
4415 Utf8Str newPath(strNewPath);
4416 newPath.append(pcszMediumPath + strOldPath.length());
4417 unconst(m->strLocationFull) = newPath;
4418
4419 LogFlowThisFunc(("locationFull.after='%s'\n", m->strLocationFull.c_str()));
4420 // we changed something
4421 return S_OK;
4422 }
4423
4424 // no change was necessary, signal error which the caller needs to interpret
4425 return VBOX_E_FILE_ERROR;
4426}
4427
4428/**
4429 * Returns the base medium of the media chain this medium is part of.
4430 *
4431 * The base medium is found by walking up the parent-child relationship axis.
4432 * If the medium doesn't have a parent (i.e. it's a base medium), it
4433 * returns itself in response to this method.
4434 *
4435 * @param aLevel Where to store the number of ancestors of this medium
4436 * (zero for the base), may be @c NULL.
4437 *
4438 * @note Locks medium tree for reading.
4439 */
4440ComObjPtr<Medium> Medium::i_getBase(uint32_t *aLevel /*= NULL*/)
4441{
4442 ComObjPtr<Medium> pBase;
4443
4444 /* it is possible that some previous/concurrent uninit has already cleared
4445 * the pVirtualBox reference, and in this case we don't need to continue */
4446 ComObjPtr<VirtualBox> pVirtualBox(m->pVirtualBox);
4447 if (!pVirtualBox)
4448 return pBase;
4449
4450 /* we access m->pParent */
4451 AutoReadLock treeLock(pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4452
4453 AutoCaller autoCaller(this);
4454 AssertReturn(autoCaller.isOk(), pBase);
4455
4456 pBase = this;
4457 uint32_t level = 0;
4458
4459 if (m->pParent)
4460 {
4461 for (;;)
4462 {
4463 AutoCaller baseCaller(pBase);
4464 AssertReturn(baseCaller.isOk(), pBase);
4465
4466 if (pBase->m->pParent.isNull())
4467 break;
4468
4469 pBase = pBase->m->pParent;
4470 ++level;
4471 }
4472 }
4473
4474 if (aLevel != NULL)
4475 *aLevel = level;
4476
4477 return pBase;
4478}
4479
4480/**
4481 * Returns the depth of this medium in the media chain.
4482 *
4483 * @note Locks medium tree for reading.
4484 */
4485uint32_t Medium::i_getDepth()
4486{
4487 /* it is possible that some previous/concurrent uninit has already cleared
4488 * the pVirtualBox reference, and in this case we don't need to continue */
4489 ComObjPtr<VirtualBox> pVirtualBox(m->pVirtualBox);
4490 if (!pVirtualBox)
4491 return 1;
4492
4493 /* we access m->pParent */
4494 AutoReadLock treeLock(pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4495
4496 uint32_t cDepth = 0;
4497 ComObjPtr<Medium> pMedium(this);
4498 while (!pMedium.isNull())
4499 {
4500 AutoCaller autoCaller(this);
4501 AssertReturn(autoCaller.isOk(), cDepth + 1);
4502
4503 pMedium = pMedium->m->pParent;
4504 cDepth++;
4505 }
4506
4507 return cDepth;
4508}
4509
4510/**
4511 * Returns @c true if this medium cannot be modified because it has
4512 * dependents (children) or is part of the snapshot. Related to the medium
4513 * type and posterity, not to the current media state.
4514 *
4515 * @note Locks this object and medium tree for reading.
4516 */
4517bool Medium::i_isReadOnly()
4518{
4519 /* it is possible that some previous/concurrent uninit has already cleared
4520 * the pVirtualBox reference, and in this case we don't need to continue */
4521 ComObjPtr<VirtualBox> pVirtualBox(m->pVirtualBox);
4522 if (!pVirtualBox)
4523 return false;
4524
4525 /* we access children */
4526 AutoReadLock treeLock(m->pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4527
4528 AutoCaller autoCaller(this);
4529 AssertComRCReturn(autoCaller.rc(), false);
4530
4531 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4532
4533 switch (m->type)
4534 {
4535 case MediumType_Normal:
4536 {
4537 if (i_getChildren().size() != 0)
4538 return true;
4539
4540 for (BackRefList::const_iterator it = m->backRefs.begin();
4541 it != m->backRefs.end(); ++it)
4542 if (it->llSnapshotIds.size() != 0)
4543 return true;
4544
4545 if (m->variant & MediumVariant_VmdkStreamOptimized)
4546 return true;
4547
4548 return false;
4549 }
4550 case MediumType_Immutable:
4551 case MediumType_MultiAttach:
4552 return true;
4553 case MediumType_Writethrough:
4554 case MediumType_Shareable:
4555 case MediumType_Readonly: /* explicit readonly media has no diffs */
4556 return false;
4557 default:
4558 break;
4559 }
4560
4561 AssertFailedReturn(false);
4562}
4563
4564/**
4565 * Internal method to return the medium's size. Must have caller + locking!
4566 * @return
4567 */
4568void Medium::i_updateId(const Guid &id)
4569{
4570 unconst(m->id) = id;
4571}
4572
4573/**
4574 * Saves the settings of one medium.
4575 *
4576 * @note Caller MUST take care of the medium tree lock and caller.
4577 *
4578 * @param data Settings struct to be updated.
4579 * @param strHardDiskFolder Folder for which paths should be relative.
4580 */
4581void Medium::i_saveSettingsOne(settings::Medium &data, const Utf8Str &strHardDiskFolder)
4582{
4583 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4584
4585 data.uuid = m->id;
4586
4587 // make path relative if needed
4588 if ( !strHardDiskFolder.isEmpty()
4589 && RTPathStartsWith(m->strLocationFull.c_str(), strHardDiskFolder.c_str())
4590 )
4591 data.strLocation = m->strLocationFull.substr(strHardDiskFolder.length() + 1);
4592 else
4593 data.strLocation = m->strLocationFull;
4594 data.strFormat = m->strFormat;
4595
4596 /* optional, only for diffs, default is false */
4597 if (m->pParent)
4598 data.fAutoReset = m->autoReset;
4599 else
4600 data.fAutoReset = false;
4601
4602 /* optional */
4603 data.strDescription = m->strDescription;
4604
4605 /* optional properties */
4606 data.properties.clear();
4607
4608 /* handle iSCSI initiator secrets transparently */
4609 bool fHaveInitiatorSecretEncrypted = false;
4610 Utf8Str strCiphertext;
4611 settings::StringsMap::const_iterator itPln = m->mapProperties.find("InitiatorSecret");
4612 if ( itPln != m->mapProperties.end()
4613 && !itPln->second.isEmpty())
4614 {
4615 /* Encrypt the plain secret. If that does not work (i.e. no or wrong settings key
4616 * specified), just use the encrypted secret (if there is any). */
4617 int rc = m->pVirtualBox->i_encryptSetting(itPln->second, &strCiphertext);
4618 if (RT_SUCCESS(rc))
4619 fHaveInitiatorSecretEncrypted = true;
4620 }
4621 for (settings::StringsMap::const_iterator it = m->mapProperties.begin();
4622 it != m->mapProperties.end();
4623 ++it)
4624 {
4625 /* only save properties that have non-default values */
4626 if (!it->second.isEmpty())
4627 {
4628 const Utf8Str &name = it->first;
4629 const Utf8Str &value = it->second;
4630 /* do NOT store the plain InitiatorSecret */
4631 if ( !fHaveInitiatorSecretEncrypted
4632 || !name.equals("InitiatorSecret"))
4633 data.properties[name] = value;
4634 }
4635 }
4636 if (fHaveInitiatorSecretEncrypted)
4637 data.properties["InitiatorSecretEncrypted"] = strCiphertext;
4638
4639 /* only for base media */
4640 if (m->pParent.isNull())
4641 data.hdType = m->type;
4642}
4643
4644/**
4645 * Saves medium data by putting it into the provided data structure.
4646 * Recurses over all children to save their settings, too.
4647 *
4648 * @param data Settings struct to be updated.
4649 * @param strHardDiskFolder Folder for which paths should be relative.
4650 *
4651 * @note Locks this object, medium tree and children for reading.
4652 */
4653HRESULT Medium::i_saveSettings(settings::Medium &data,
4654 const Utf8Str &strHardDiskFolder)
4655{
4656 /* we access m->pParent */
4657 AutoReadLock treeLock(m->pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4658
4659 AutoCaller autoCaller(this);
4660 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4661
4662 i_saveSettingsOne(data, strHardDiskFolder);
4663
4664 /* save all children */
4665 settings::MediaList &llSettingsChildren = data.llChildren;
4666 for (MediaList::const_iterator it = i_getChildren().begin();
4667 it != i_getChildren().end();
4668 ++it)
4669 {
4670 // Use the element straight in the list to reduce both unnecessary
4671 // deep copying (when unwinding the recursion the entire medium
4672 // settings sub-tree is copied) and the stack footprint (the settings
4673 // need almost 1K, and there can be VMs with long image chains.
4674 llSettingsChildren.push_back(settings::Medium::Empty);
4675 HRESULT rc = (*it)->i_saveSettings(llSettingsChildren.back(), strHardDiskFolder);
4676 if (FAILED(rc))
4677 {
4678 llSettingsChildren.pop_back();
4679 return rc;
4680 }
4681 }
4682
4683 return S_OK;
4684}
4685
4686/**
4687 * Constructs a medium lock list for this medium. The lock is not taken.
4688 *
4689 * @note Caller MUST NOT hold the media tree or medium lock.
4690 *
4691 * @param fFailIfInaccessible If true, this fails with an error if a medium is inaccessible. If false,
4692 * inaccessible media are silently skipped and not locked (i.e. their state remains "Inaccessible");
4693 * this is necessary for a VM's removable media VM startup for which we do not want to fail.
4694 * @param pToLockWrite If not NULL, associate a write lock with this medium object.
4695 * @param fMediumLockWriteAll Whether to associate a write lock to all other media too.
4696 * @param pToBeParent Medium which will become the parent of this medium.
4697 * @param mediumLockList Where to store the resulting list.
4698 */
4699HRESULT Medium::i_createMediumLockList(bool fFailIfInaccessible,
4700 Medium *pToLockWrite,
4701 bool fMediumLockWriteAll,
4702 Medium *pToBeParent,
4703 MediumLockList &mediumLockList)
4704{
4705 /** @todo r=klaus this needs to be reworked, as the code below uses
4706 * i_getParent without holding the tree lock, and changing this is
4707 * a significant amount of effort. */
4708 Assert(!m->pVirtualBox->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4709 Assert(!isWriteLockOnCurrentThread());
4710
4711 AutoCaller autoCaller(this);
4712 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4713
4714 HRESULT rc = S_OK;
4715
4716 /* paranoid sanity checking if the medium has a to-be parent medium */
4717 if (pToBeParent)
4718 {
4719 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4720 ComAssertRet(i_getParent().isNull(), E_FAIL);
4721 ComAssertRet(i_getChildren().size() == 0, E_FAIL);
4722 }
4723
4724 ErrorInfoKeeper eik;
4725 MultiResult mrc(S_OK);
4726
4727 ComObjPtr<Medium> pMedium = this;
4728 while (!pMedium.isNull())
4729 {
4730 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
4731
4732 /* Accessibility check must be first, otherwise locking interferes
4733 * with getting the medium state. Lock lists are not created for
4734 * fun, and thus getting the medium status is no luxury. */
4735 MediumState_T mediumState = pMedium->i_getState();
4736 if (mediumState == MediumState_Inaccessible)
4737 {
4738 alock.release();
4739 rc = pMedium->i_queryInfo(false /* fSetImageId */, false /* fSetParentId */,
4740 autoCaller);
4741 alock.acquire();
4742 if (FAILED(rc)) return rc;
4743
4744 mediumState = pMedium->i_getState();
4745 if (mediumState == MediumState_Inaccessible)
4746 {
4747 // ignore inaccessible ISO media and silently return S_OK,
4748 // otherwise VM startup (esp. restore) may fail without good reason
4749 if (!fFailIfInaccessible)
4750 return S_OK;
4751
4752 // otherwise report an error
4753 Bstr error;
4754 rc = pMedium->COMGETTER(LastAccessError)(error.asOutParam());
4755 if (FAILED(rc)) return rc;
4756
4757 /* collect multiple errors */
4758 eik.restore();
4759 Assert(!error.isEmpty());
4760 mrc = setError(E_FAIL,
4761 "%ls",
4762 error.raw());
4763 // error message will be something like
4764 // "Could not open the medium ... VD: error VERR_FILE_NOT_FOUND opening image file ... (VERR_FILE_NOT_FOUND).
4765 eik.fetch();
4766 }
4767 }
4768
4769 if (pMedium == pToLockWrite)
4770 mediumLockList.Prepend(pMedium, true);
4771 else
4772 mediumLockList.Prepend(pMedium, fMediumLockWriteAll);
4773
4774 pMedium = pMedium->i_getParent();
4775 if (pMedium.isNull() && pToBeParent)
4776 {
4777 pMedium = pToBeParent;
4778 pToBeParent = NULL;
4779 }
4780 }
4781
4782 return mrc;
4783}
4784
4785/**
4786 * Creates a new differencing storage unit using the format of the given target
4787 * medium and the location. Note that @c aTarget must be NotCreated.
4788 *
4789 * The @a aMediumLockList parameter contains the associated medium lock list,
4790 * which must be in locked state. If @a aWait is @c true then the caller is
4791 * responsible for unlocking.
4792 *
4793 * If @a aProgress is not NULL but the object it points to is @c null then a
4794 * new progress object will be created and assigned to @a *aProgress on
4795 * success, otherwise the existing progress object is used. If @a aProgress is
4796 * NULL, then no progress object is created/used at all.
4797 *
4798 * When @a aWait is @c false, this method will create a thread to perform the
4799 * create operation asynchronously and will return immediately. Otherwise, it
4800 * will perform the operation on the calling thread and will not return to the
4801 * caller until the operation is completed. Note that @a aProgress cannot be
4802 * NULL when @a aWait is @c false (this method will assert in this case).
4803 *
4804 * @param aTarget Target medium.
4805 * @param aVariant Precise medium variant to create.
4806 * @param aMediumLockList List of media which should be locked.
4807 * @param aProgress Where to find/store a Progress object to track
4808 * operation completion.
4809 * @param aWait @c true if this method should block instead of
4810 * creating an asynchronous thread.
4811 *
4812 * @note Locks this object and @a aTarget for writing.
4813 */
4814HRESULT Medium::i_createDiffStorage(ComObjPtr<Medium> &aTarget,
4815 MediumVariant_T aVariant,
4816 MediumLockList *aMediumLockList,
4817 ComObjPtr<Progress> *aProgress,
4818 bool aWait)
4819{
4820 AssertReturn(!aTarget.isNull(), E_FAIL);
4821 AssertReturn(aMediumLockList, E_FAIL);
4822 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
4823
4824 AutoCaller autoCaller(this);
4825 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4826
4827 AutoCaller targetCaller(aTarget);
4828 if (FAILED(targetCaller.rc())) return targetCaller.rc();
4829
4830 HRESULT rc = S_OK;
4831 ComObjPtr<Progress> pProgress;
4832 Medium::Task *pTask = NULL;
4833
4834 try
4835 {
4836 AutoMultiWriteLock2 alock(this, aTarget COMMA_LOCKVAL_SRC_POS);
4837
4838 ComAssertThrow( m->type != MediumType_Writethrough
4839 && m->type != MediumType_Shareable
4840 && m->type != MediumType_Readonly, E_FAIL);
4841 ComAssertThrow(m->state == MediumState_LockedRead, E_FAIL);
4842
4843 if (aTarget->m->state != MediumState_NotCreated)
4844 throw aTarget->i_setStateError();
4845
4846 /* Check that the medium is not attached to the current state of
4847 * any VM referring to it. */
4848 for (BackRefList::const_iterator it = m->backRefs.begin();
4849 it != m->backRefs.end();
4850 ++it)
4851 {
4852 if (it->fInCurState)
4853 {
4854 /* Note: when a VM snapshot is being taken, all normal media
4855 * attached to the VM in the current state will be, as an
4856 * exception, also associated with the snapshot which is about
4857 * to create (see SnapshotMachine::init()) before deassociating
4858 * them from the current state (which takes place only on
4859 * success in Machine::fixupHardDisks()), so that the size of
4860 * snapshotIds will be 1 in this case. The extra condition is
4861 * used to filter out this legal situation. */
4862 if (it->llSnapshotIds.size() == 0)
4863 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4864 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"),
4865 m->strLocationFull.c_str(), it->machineId.raw());
4866
4867 Assert(it->llSnapshotIds.size() == 1);
4868 }
4869 }
4870
4871 if (aProgress != NULL)
4872 {
4873 /* use the existing progress object... */
4874 pProgress = *aProgress;
4875
4876 /* ...but create a new one if it is null */
4877 if (pProgress.isNull())
4878 {
4879 pProgress.createObject();
4880 rc = pProgress->init(m->pVirtualBox,
4881 static_cast<IMedium*>(this),
4882 BstrFmt(tr("Creating differencing medium storage unit '%s'"),
4883 aTarget->m->strLocationFull.c_str()).raw(),
4884 TRUE /* aCancelable */);
4885 if (FAILED(rc))
4886 throw rc;
4887 }
4888 }
4889
4890 /* setup task object to carry out the operation sync/async */
4891 pTask = new Medium::CreateDiffTask(this, pProgress, aTarget, aVariant,
4892 aMediumLockList,
4893 aWait /* fKeepMediumLockList */);
4894 rc = pTask->rc();
4895 AssertComRC(rc);
4896 if (FAILED(rc))
4897 throw rc;
4898
4899 /* register a task (it will deregister itself when done) */
4900 ++m->numCreateDiffTasks;
4901 Assert(m->numCreateDiffTasks != 0); /* overflow? */
4902
4903 aTarget->m->state = MediumState_Creating;
4904 }
4905 catch (HRESULT aRC) { rc = aRC; }
4906
4907 if (SUCCEEDED(rc))
4908 {
4909 if (aWait)
4910 {
4911 rc = pTask->runNow();
4912
4913 delete pTask;
4914 }
4915 else
4916 rc = pTask->createThread();
4917
4918 if (SUCCEEDED(rc) && aProgress != NULL)
4919 *aProgress = pProgress;
4920 }
4921 else if (pTask != NULL)
4922 delete pTask;
4923
4924 return rc;
4925}
4926
4927/**
4928 * Returns a preferred format for differencing media.
4929 */
4930Utf8Str Medium::i_getPreferredDiffFormat()
4931{
4932 AutoCaller autoCaller(this);
4933 AssertComRCReturn(autoCaller.rc(), Utf8Str::Empty);
4934
4935 /* check that our own format supports diffs */
4936 if (!(m->formatObj->i_getCapabilities() & MediumFormatCapabilities_Differencing))
4937 {
4938 /* use the default format if not */
4939 Utf8Str tmp;
4940 m->pVirtualBox->i_getDefaultHardDiskFormat(tmp);
4941 return tmp;
4942 }
4943
4944 /* m->strFormat is const, no need to lock */
4945 return m->strFormat;
4946}
4947
4948/**
4949 * Returns a preferred variant for differencing media.
4950 */
4951MediumVariant_T Medium::i_getPreferredDiffVariant()
4952{
4953 AutoCaller autoCaller(this);
4954 AssertComRCReturn(autoCaller.rc(), MediumVariant_Standard);
4955
4956 /* check that our own format supports diffs */
4957 if (!(m->formatObj->i_getCapabilities() & MediumFormatCapabilities_Differencing))
4958 return MediumVariant_Standard;
4959
4960 /* m->variant is const, no need to lock */
4961 ULONG mediumVariantFlags = (ULONG)m->variant;
4962 mediumVariantFlags &= ~(MediumVariant_Fixed | MediumVariant_VmdkStreamOptimized);
4963 mediumVariantFlags |= MediumVariant_Diff;
4964 return (MediumVariant_T)mediumVariantFlags;
4965}
4966
4967/**
4968 * Implementation for the public Medium::Close() with the exception of calling
4969 * VirtualBox::saveRegistries(), in case someone wants to call this for several
4970 * media.
4971 *
4972 * After this returns with success, uninit() has been called on the medium, and
4973 * the object is no longer usable ("not ready" state).
4974 *
4975 * @param autoCaller AutoCaller instance which must have been created on the caller's
4976 * stack for this medium. This gets released hereupon
4977 * which the Medium instance gets uninitialized.
4978 * @return
4979 */
4980HRESULT Medium::i_close(AutoCaller &autoCaller)
4981{
4982 // must temporarily drop the caller, need the tree lock first
4983 autoCaller.release();
4984
4985 // we're accessing parent/child and backrefs, so lock the tree first, then ourselves
4986 AutoMultiWriteLock2 multilock(&m->pVirtualBox->i_getMediaTreeLockHandle(),
4987 this->lockHandle()
4988 COMMA_LOCKVAL_SRC_POS);
4989
4990 autoCaller.add();
4991 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4992
4993 LogFlowFunc(("ENTER for %s\n", i_getLocationFull().c_str()));
4994
4995 bool wasCreated = true;
4996
4997 switch (m->state)
4998 {
4999 case MediumState_NotCreated:
5000 wasCreated = false;
5001 break;
5002 case MediumState_Created:
5003 case MediumState_Inaccessible:
5004 break;
5005 default:
5006 return i_setStateError();
5007 }
5008
5009 if (m->backRefs.size() != 0)
5010 return setError(VBOX_E_OBJECT_IN_USE,
5011 tr("Medium '%s' cannot be closed because it is still attached to %d virtual machines"),
5012 m->strLocationFull.c_str(), m->backRefs.size());
5013
5014 // perform extra media-dependent close checks
5015 HRESULT rc = i_canClose();
5016 if (FAILED(rc)) return rc;
5017
5018 m->fClosing = true;
5019
5020 if (wasCreated)
5021 {
5022 // remove from the list of known media before performing actual
5023 // uninitialization (to keep the media registry consistent on
5024 // failure to do so)
5025 rc = i_unregisterWithVirtualBox();
5026 if (FAILED(rc)) return rc;
5027
5028 multilock.release();
5029 // Release the AutoCaller now, as otherwise uninit() will simply hang.
5030 // Needs to be done before mark the registries as modified and saving
5031 // the registry, as otherwise there may be a deadlock with someone else
5032 // closing this object while we're in i_saveModifiedRegistries(), which
5033 // needs the media tree lock, which the other thread holds until after
5034 // uninit() below.
5035 autoCaller.release();
5036 i_markRegistriesModified();
5037 m->pVirtualBox->i_saveModifiedRegistries();
5038 }
5039 else
5040 {
5041 multilock.release();
5042 // release the AutoCaller, as otherwise uninit() will simply hang
5043 autoCaller.release();
5044 }
5045
5046 // Keep the locks held until after uninit, as otherwise the consistency
5047 // of the medium tree cannot be guaranteed.
5048 uninit();
5049
5050 LogFlowFuncLeave();
5051
5052 return rc;
5053}
5054
5055/**
5056 * Deletes the medium storage unit.
5057 *
5058 * If @a aProgress is not NULL but the object it points to is @c null then a new
5059 * progress object will be created and assigned to @a *aProgress on success,
5060 * otherwise the existing progress object is used. If Progress is NULL, then no
5061 * progress object is created/used at all.
5062 *
5063 * When @a aWait is @c false, this method will create a thread to perform the
5064 * delete operation asynchronously and will return immediately. Otherwise, it
5065 * will perform the operation on the calling thread and will not return to the
5066 * caller until the operation is completed. Note that @a aProgress cannot be
5067 * NULL when @a aWait is @c false (this method will assert in this case).
5068 *
5069 * @param aProgress Where to find/store a Progress object to track operation
5070 * completion.
5071 * @param aWait @c true if this method should block instead of creating
5072 * an asynchronous thread.
5073 *
5074 * @note Locks mVirtualBox and this object for writing. Locks medium tree for
5075 * writing.
5076 */
5077HRESULT Medium::i_deleteStorage(ComObjPtr<Progress> *aProgress,
5078 bool aWait)
5079{
5080 /** @todo r=klaus The code below needs to be double checked with regard
5081 * to lock order violations, it probably causes lock order issues related
5082 * to the AutoCaller usage. */
5083 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
5084
5085 AutoCaller autoCaller(this);
5086 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5087
5088 HRESULT rc = S_OK;
5089 ComObjPtr<Progress> pProgress;
5090 Medium::Task *pTask = NULL;
5091
5092 try
5093 {
5094 /* we're accessing the media tree, and canClose() needs it too */
5095 AutoMultiWriteLock2 multilock(&m->pVirtualBox->i_getMediaTreeLockHandle(),
5096 this->lockHandle()
5097 COMMA_LOCKVAL_SRC_POS);
5098 LogFlowThisFunc(("aWait=%RTbool locationFull=%s\n", aWait, i_getLocationFull().c_str() ));
5099
5100 if ( !(m->formatObj->i_getCapabilities() & ( MediumFormatCapabilities_CreateDynamic
5101 | MediumFormatCapabilities_CreateFixed)))
5102 throw setError(VBOX_E_NOT_SUPPORTED,
5103 tr("Medium format '%s' does not support storage deletion"),
5104 m->strFormat.c_str());
5105
5106 /* Wait for a concurrently running Medium::i_queryInfo to complete. */
5107 /** @todo r=klaus would be great if this could be moved to the async
5108 * part of the operation as it can take quite a while */
5109 if (m->queryInfoRunning)
5110 {
5111 while (m->queryInfoRunning)
5112 {
5113 multilock.release();
5114 /* Must not hold the media tree lock or the object lock, as
5115 * Medium::i_queryInfo needs this lock and thus we would run
5116 * into a deadlock here. */
5117 Assert(!m->pVirtualBox->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5118 Assert(!isWriteLockOnCurrentThread());
5119 {
5120 AutoReadLock qlock(m->queryInfoSem COMMA_LOCKVAL_SRC_POS);
5121 }
5122 multilock.acquire();
5123 }
5124 }
5125
5126 /* Note that we are fine with Inaccessible state too: a) for symmetry
5127 * with create calls and b) because it doesn't really harm to try, if
5128 * it is really inaccessible, the delete operation will fail anyway.
5129 * Accepting Inaccessible state is especially important because all
5130 * registered media are initially Inaccessible upon VBoxSVC startup
5131 * until COMGETTER(RefreshState) is called. Accept Deleting state
5132 * because some callers need to put the medium in this state early
5133 * to prevent races. */
5134 switch (m->state)
5135 {
5136 case MediumState_Created:
5137 case MediumState_Deleting:
5138 case MediumState_Inaccessible:
5139 break;
5140 default:
5141 throw i_setStateError();
5142 }
5143
5144 if (m->backRefs.size() != 0)
5145 {
5146 Utf8Str strMachines;
5147 for (BackRefList::const_iterator it = m->backRefs.begin();
5148 it != m->backRefs.end();
5149 ++it)
5150 {
5151 const BackRef &b = *it;
5152 if (strMachines.length())
5153 strMachines.append(", ");
5154 strMachines.append(b.machineId.toString().c_str());
5155 }
5156#ifdef DEBUG
5157 i_dumpBackRefs();
5158#endif
5159 throw setError(VBOX_E_OBJECT_IN_USE,
5160 tr("Cannot delete storage: medium '%s' is still attached to the following %d virtual machine(s): %s"),
5161 m->strLocationFull.c_str(),
5162 m->backRefs.size(),
5163 strMachines.c_str());
5164 }
5165
5166 rc = i_canClose();
5167 if (FAILED(rc))
5168 throw rc;
5169
5170 /* go to Deleting state, so that the medium is not actually locked */
5171 if (m->state != MediumState_Deleting)
5172 {
5173 rc = i_markForDeletion();
5174 if (FAILED(rc))
5175 throw rc;
5176 }
5177
5178 /* Build the medium lock list. */
5179 MediumLockList *pMediumLockList(new MediumLockList());
5180 multilock.release();
5181 rc = i_createMediumLockList(true /* fFailIfInaccessible */,
5182 this /* pToLockWrite */,
5183 false /* fMediumLockWriteAll */,
5184 NULL,
5185 *pMediumLockList);
5186 multilock.acquire();
5187 if (FAILED(rc))
5188 {
5189 delete pMediumLockList;
5190 throw rc;
5191 }
5192
5193 multilock.release();
5194 rc = pMediumLockList->Lock();
5195 multilock.acquire();
5196 if (FAILED(rc))
5197 {
5198 delete pMediumLockList;
5199 throw setError(rc,
5200 tr("Failed to lock media when deleting '%s'"),
5201 i_getLocationFull().c_str());
5202 }
5203
5204 /* try to remove from the list of known media before performing
5205 * actual deletion (we favor the consistency of the media registry
5206 * which would have been broken if unregisterWithVirtualBox() failed
5207 * after we successfully deleted the storage) */
5208 rc = i_unregisterWithVirtualBox();
5209 if (FAILED(rc))
5210 throw rc;
5211 // no longer need lock
5212 multilock.release();
5213 i_markRegistriesModified();
5214
5215 if (aProgress != NULL)
5216 {
5217 /* use the existing progress object... */
5218 pProgress = *aProgress;
5219
5220 /* ...but create a new one if it is null */
5221 if (pProgress.isNull())
5222 {
5223 pProgress.createObject();
5224 rc = pProgress->init(m->pVirtualBox,
5225 static_cast<IMedium*>(this),
5226 BstrFmt(tr("Deleting medium storage unit '%s'"), m->strLocationFull.c_str()).raw(),
5227 FALSE /* aCancelable */);
5228 if (FAILED(rc))
5229 throw rc;
5230 }
5231 }
5232
5233 /* setup task object to carry out the operation sync/async */
5234 pTask = new Medium::DeleteTask(this, pProgress, pMediumLockList);
5235 rc = pTask->rc();
5236 AssertComRC(rc);
5237 if (FAILED(rc))
5238 throw rc;
5239 }
5240 catch (HRESULT aRC) { rc = aRC; }
5241
5242 if (SUCCEEDED(rc))
5243 {
5244 if (aWait)
5245 {
5246 rc = pTask->runNow();
5247
5248 delete pTask;
5249 }
5250 else
5251 rc = pTask->createThread();
5252
5253 if (SUCCEEDED(rc) && aProgress != NULL)
5254 *aProgress = pProgress;
5255
5256 }
5257 else
5258 {
5259 if (pTask)
5260 delete pTask;
5261
5262 /* Undo deleting state if necessary. */
5263 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5264 /* Make sure that any error signalled by unmarkForDeletion() is not
5265 * ending up in the error list (if the caller uses MultiResult). It
5266 * usually is spurious, as in most cases the medium hasn't been marked
5267 * for deletion when the error was thrown above. */
5268 ErrorInfoKeeper eik;
5269 i_unmarkForDeletion();
5270 }
5271
5272 return rc;
5273}
5274
5275/**
5276 * Mark a medium for deletion.
5277 *
5278 * @note Caller must hold the write lock on this medium!
5279 */
5280HRESULT Medium::i_markForDeletion()
5281{
5282 ComAssertRet(isWriteLockOnCurrentThread(), E_FAIL);
5283 switch (m->state)
5284 {
5285 case MediumState_Created:
5286 case MediumState_Inaccessible:
5287 m->preLockState = m->state;
5288 m->state = MediumState_Deleting;
5289 return S_OK;
5290 default:
5291 return i_setStateError();
5292 }
5293}
5294
5295/**
5296 * Removes the "mark for deletion".
5297 *
5298 * @note Caller must hold the write lock on this medium!
5299 */
5300HRESULT Medium::i_unmarkForDeletion()
5301{
5302 ComAssertRet(isWriteLockOnCurrentThread(), E_FAIL);
5303 switch (m->state)
5304 {
5305 case MediumState_Deleting:
5306 m->state = m->preLockState;
5307 return S_OK;
5308 default:
5309 return i_setStateError();
5310 }
5311}
5312
5313/**
5314 * Mark a medium for deletion which is in locked state.
5315 *
5316 * @note Caller must hold the write lock on this medium!
5317 */
5318HRESULT Medium::i_markLockedForDeletion()
5319{
5320 ComAssertRet(isWriteLockOnCurrentThread(), E_FAIL);
5321 if ( ( m->state == MediumState_LockedRead
5322 || m->state == MediumState_LockedWrite)
5323 && m->preLockState == MediumState_Created)
5324 {
5325 m->preLockState = MediumState_Deleting;
5326 return S_OK;
5327 }
5328 else
5329 return i_setStateError();
5330}
5331
5332/**
5333 * Removes the "mark for deletion" for a medium in locked state.
5334 *
5335 * @note Caller must hold the write lock on this medium!
5336 */
5337HRESULT Medium::i_unmarkLockedForDeletion()
5338{
5339 ComAssertRet(isWriteLockOnCurrentThread(), E_FAIL);
5340 if ( ( m->state == MediumState_LockedRead
5341 || m->state == MediumState_LockedWrite)
5342 && m->preLockState == MediumState_Deleting)
5343 {
5344 m->preLockState = MediumState_Created;
5345 return S_OK;
5346 }
5347 else
5348 return i_setStateError();
5349}
5350
5351/**
5352 * Queries the preferred merge direction from this to the other medium, i.e.
5353 * the one which requires the least amount of I/O and therefore time and
5354 * disk consumption.
5355 *
5356 * @returns Status code.
5357 * @retval E_FAIL in case determining the merge direction fails for some reason,
5358 * for example if getting the size of the media fails. There is no
5359 * error set though and the caller is free to continue to find out
5360 * what was going wrong later. Leaves fMergeForward unset.
5361 * @retval VBOX_E_INVALID_OBJECT_STATE if both media are not related to each other
5362 * An error is set.
5363 * @param pOther The other medium to merge with.
5364 * @param fMergeForward Resulting preferred merge direction (out).
5365 */
5366HRESULT Medium::i_queryPreferredMergeDirection(const ComObjPtr<Medium> &pOther,
5367 bool &fMergeForward)
5368{
5369 /** @todo r=klaus The code below needs to be double checked with regard
5370 * to lock order violations, it probably causes lock order issues related
5371 * to the AutoCaller usage. Likewise the code using this method seems
5372 * problematic. */
5373 AssertReturn(pOther != NULL, E_FAIL);
5374 AssertReturn(pOther != this, E_FAIL);
5375
5376 AutoCaller autoCaller(this);
5377 AssertComRCReturnRC(autoCaller.rc());
5378
5379 AutoCaller otherCaller(pOther);
5380 AssertComRCReturnRC(otherCaller.rc());
5381
5382 HRESULT rc = S_OK;
5383 bool fThisParent = false; /**<< Flag whether this medium is the parent of pOther. */
5384
5385 try
5386 {
5387 // locking: we need the tree lock first because we access parent pointers
5388 AutoWriteLock treeLock(m->pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5389
5390 /* more sanity checking and figuring out the current merge direction */
5391 ComObjPtr<Medium> pMedium = i_getParent();
5392 while (!pMedium.isNull() && pMedium != pOther)
5393 pMedium = pMedium->i_getParent();
5394 if (pMedium == pOther)
5395 fThisParent = false;
5396 else
5397 {
5398 pMedium = pOther->i_getParent();
5399 while (!pMedium.isNull() && pMedium != this)
5400 pMedium = pMedium->i_getParent();
5401 if (pMedium == this)
5402 fThisParent = true;
5403 else
5404 {
5405 Utf8Str tgtLoc;
5406 {
5407 AutoReadLock alock(pOther COMMA_LOCKVAL_SRC_POS);
5408 tgtLoc = pOther->i_getLocationFull();
5409 }
5410
5411 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5412 throw setError(VBOX_E_INVALID_OBJECT_STATE,
5413 tr("Media '%s' and '%s' are unrelated"),
5414 m->strLocationFull.c_str(), tgtLoc.c_str());
5415 }
5416 }
5417
5418 /*
5419 * Figure out the preferred merge direction. The current way is to
5420 * get the current sizes of file based images and select the merge
5421 * direction depending on the size.
5422 *
5423 * Can't use the VD API to get current size here as the media might
5424 * be write locked by a running VM. Resort to RTFileQuerySize().
5425 */
5426 int vrc = VINF_SUCCESS;
5427 uint64_t cbMediumThis = 0;
5428 uint64_t cbMediumOther = 0;
5429
5430 if (i_isMediumFormatFile() && pOther->i_isMediumFormatFile())
5431 {
5432 vrc = RTFileQuerySize(this->i_getLocationFull().c_str(), &cbMediumThis);
5433 if (RT_SUCCESS(vrc))
5434 {
5435 vrc = RTFileQuerySize(pOther->i_getLocationFull().c_str(),
5436 &cbMediumOther);
5437 }
5438
5439 if (RT_FAILURE(vrc))
5440 rc = E_FAIL;
5441 else
5442 {
5443 /*
5444 * Check which merge direction might be more optimal.
5445 * This method is not bullet proof of course as there might
5446 * be overlapping blocks in the images so the file size is
5447 * not the best indicator but it is good enough for our purpose
5448 * and everything else is too complicated, especially when the
5449 * media are used by a running VM.
5450 */
5451 bool fMergeIntoThis = cbMediumThis > cbMediumOther;
5452 fMergeForward = fMergeIntoThis != fThisParent;
5453 }
5454 }
5455 }
5456 catch (HRESULT aRC) { rc = aRC; }
5457
5458 return rc;
5459}
5460
5461/**
5462 * Prepares this (source) medium, target medium and all intermediate media
5463 * for the merge operation.
5464 *
5465 * This method is to be called prior to calling the #mergeTo() to perform
5466 * necessary consistency checks and place involved media to appropriate
5467 * states. If #mergeTo() is not called or fails, the state modifications
5468 * performed by this method must be undone by #i_cancelMergeTo().
5469 *
5470 * See #mergeTo() for more information about merging.
5471 *
5472 * @param pTarget Target medium.
5473 * @param aMachineId Allowed machine attachment. NULL means do not check.
5474 * @param aSnapshotId Allowed snapshot attachment. NULL or empty UUID means
5475 * do not check.
5476 * @param fLockMedia Flag whether to lock the medium lock list or not.
5477 * If set to false and the medium lock list locking fails
5478 * later you must call #i_cancelMergeTo().
5479 * @param fMergeForward Resulting merge direction (out).
5480 * @param pParentForTarget New parent for target medium after merge (out).
5481 * @param aChildrenToReparent Medium lock list containing all children of the
5482 * source which will have to be reparented to the target
5483 * after merge (out).
5484 * @param aMediumLockList Medium locking information (out).
5485 *
5486 * @note Locks medium tree for reading. Locks this object, aTarget and all
5487 * intermediate media for writing.
5488 */
5489HRESULT Medium::i_prepareMergeTo(const ComObjPtr<Medium> &pTarget,
5490 const Guid *aMachineId,
5491 const Guid *aSnapshotId,
5492 bool fLockMedia,
5493 bool &fMergeForward,
5494 ComObjPtr<Medium> &pParentForTarget,
5495 MediumLockList * &aChildrenToReparent,
5496 MediumLockList * &aMediumLockList)
5497{
5498 /** @todo r=klaus The code below needs to be double checked with regard
5499 * to lock order violations, it probably causes lock order issues related
5500 * to the AutoCaller usage. Likewise the code using this method seems
5501 * problematic. */
5502 AssertReturn(pTarget != NULL, E_FAIL);
5503 AssertReturn(pTarget != this, E_FAIL);
5504
5505 AutoCaller autoCaller(this);
5506 AssertComRCReturnRC(autoCaller.rc());
5507
5508 AutoCaller targetCaller(pTarget);
5509 AssertComRCReturnRC(targetCaller.rc());
5510
5511 HRESULT rc = S_OK;
5512 fMergeForward = false;
5513 pParentForTarget.setNull();
5514 Assert(aChildrenToReparent == NULL);
5515 aChildrenToReparent = NULL;
5516 Assert(aMediumLockList == NULL);
5517 aMediumLockList = NULL;
5518
5519 try
5520 {
5521 // locking: we need the tree lock first because we access parent pointers
5522 AutoWriteLock treeLock(m->pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5523
5524 /* more sanity checking and figuring out the merge direction */
5525 ComObjPtr<Medium> pMedium = i_getParent();
5526 while (!pMedium.isNull() && pMedium != pTarget)
5527 pMedium = pMedium->i_getParent();
5528 if (pMedium == pTarget)
5529 fMergeForward = false;
5530 else
5531 {
5532 pMedium = pTarget->i_getParent();
5533 while (!pMedium.isNull() && pMedium != this)
5534 pMedium = pMedium->i_getParent();
5535 if (pMedium == this)
5536 fMergeForward = true;
5537 else
5538 {
5539 Utf8Str tgtLoc;
5540 {
5541 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
5542 tgtLoc = pTarget->i_getLocationFull();
5543 }
5544
5545 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5546 throw setError(VBOX_E_INVALID_OBJECT_STATE,
5547 tr("Media '%s' and '%s' are unrelated"),
5548 m->strLocationFull.c_str(), tgtLoc.c_str());
5549 }
5550 }
5551
5552 /* Build the lock list. */
5553 aMediumLockList = new MediumLockList();
5554 treeLock.release();
5555 if (fMergeForward)
5556 rc = pTarget->i_createMediumLockList(true /* fFailIfInaccessible */,
5557 pTarget /* pToLockWrite */,
5558 false /* fMediumLockWriteAll */,
5559 NULL,
5560 *aMediumLockList);
5561 else
5562 rc = i_createMediumLockList(true /* fFailIfInaccessible */,
5563 pTarget /* pToLockWrite */,
5564 false /* fMediumLockWriteAll */,
5565 NULL,
5566 *aMediumLockList);
5567 treeLock.acquire();
5568 if (FAILED(rc))
5569 throw rc;
5570
5571 /* Sanity checking, must be after lock list creation as it depends on
5572 * valid medium states. The medium objects must be accessible. Only
5573 * do this if immediate locking is requested, otherwise it fails when
5574 * we construct a medium lock list for an already running VM. Snapshot
5575 * deletion uses this to simplify its life. */
5576 if (fLockMedia)
5577 {
5578 {
5579 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5580 if (m->state != MediumState_Created)
5581 throw i_setStateError();
5582 }
5583 {
5584 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
5585 if (pTarget->m->state != MediumState_Created)
5586 throw pTarget->i_setStateError();
5587 }
5588 }
5589
5590 /* check medium attachment and other sanity conditions */
5591 if (fMergeForward)
5592 {
5593 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5594 if (i_getChildren().size() > 1)
5595 {
5596 throw setError(VBOX_E_INVALID_OBJECT_STATE,
5597 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
5598 m->strLocationFull.c_str(), i_getChildren().size());
5599 }
5600 /* One backreference is only allowed if the machine ID is not empty
5601 * and it matches the machine the medium is attached to (including
5602 * the snapshot ID if not empty). */
5603 if ( m->backRefs.size() != 0
5604 && ( !aMachineId
5605 || m->backRefs.size() != 1
5606 || aMachineId->isZero()
5607 || *i_getFirstMachineBackrefId() != *aMachineId
5608 || ( (!aSnapshotId || !aSnapshotId->isZero())
5609 && *i_getFirstMachineBackrefSnapshotId() != *aSnapshotId)))
5610 throw setError(VBOX_E_OBJECT_IN_USE,
5611 tr("Medium '%s' is attached to %d virtual machines"),
5612 m->strLocationFull.c_str(), m->backRefs.size());
5613 if (m->type == MediumType_Immutable)
5614 throw setError(VBOX_E_INVALID_OBJECT_STATE,
5615 tr("Medium '%s' is immutable"),
5616 m->strLocationFull.c_str());
5617 if (m->type == MediumType_MultiAttach)
5618 throw setError(VBOX_E_INVALID_OBJECT_STATE,
5619 tr("Medium '%s' is multi-attach"),
5620 m->strLocationFull.c_str());
5621 }
5622 else
5623 {
5624 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
5625 if (pTarget->i_getChildren().size() > 1)
5626 {
5627 throw setError(VBOX_E_OBJECT_IN_USE,
5628 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
5629 pTarget->m->strLocationFull.c_str(),
5630 pTarget->i_getChildren().size());
5631 }
5632 if (pTarget->m->type == MediumType_Immutable)
5633 throw setError(VBOX_E_INVALID_OBJECT_STATE,
5634 tr("Medium '%s' is immutable"),
5635 pTarget->m->strLocationFull.c_str());
5636 if (pTarget->m->type == MediumType_MultiAttach)
5637 throw setError(VBOX_E_INVALID_OBJECT_STATE,
5638 tr("Medium '%s' is multi-attach"),
5639 pTarget->m->strLocationFull.c_str());
5640 }
5641 ComObjPtr<Medium> pLast(fMergeForward ? (Medium *)pTarget : this);
5642 ComObjPtr<Medium> pLastIntermediate = pLast->i_getParent();
5643 for (pLast = pLastIntermediate;
5644 !pLast.isNull() && pLast != pTarget && pLast != this;
5645 pLast = pLast->i_getParent())
5646 {
5647 AutoReadLock alock(pLast COMMA_LOCKVAL_SRC_POS);
5648 if (pLast->i_getChildren().size() > 1)
5649 {
5650 throw setError(VBOX_E_OBJECT_IN_USE,
5651 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
5652 pLast->m->strLocationFull.c_str(),
5653 pLast->i_getChildren().size());
5654 }
5655 if (pLast->m->backRefs.size() != 0)
5656 throw setError(VBOX_E_OBJECT_IN_USE,
5657 tr("Medium '%s' is attached to %d virtual machines"),
5658 pLast->m->strLocationFull.c_str(),
5659 pLast->m->backRefs.size());
5660
5661 }
5662
5663 /* Update medium states appropriately */
5664 {
5665 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5666
5667 if (m->state == MediumState_Created)
5668 {
5669 rc = i_markForDeletion();
5670 if (FAILED(rc))
5671 throw rc;
5672 }
5673 else
5674 {
5675 if (fLockMedia)
5676 throw i_setStateError();
5677 else if ( m->state == MediumState_LockedWrite
5678 || m->state == MediumState_LockedRead)
5679 {
5680 /* Either mark it for deletion in locked state or allow
5681 * others to have done so. */
5682 if (m->preLockState == MediumState_Created)
5683 i_markLockedForDeletion();
5684 else if (m->preLockState != MediumState_Deleting)
5685 throw i_setStateError();
5686 }
5687 else
5688 throw i_setStateError();
5689 }
5690 }
5691
5692 if (fMergeForward)
5693 {
5694 /* we will need parent to reparent target */
5695 pParentForTarget = i_getParent();
5696 }
5697 else
5698 {
5699 /* we will need to reparent children of the source */
5700 aChildrenToReparent = new MediumLockList();
5701 for (MediaList::const_iterator it = i_getChildren().begin();
5702 it != i_getChildren().end();
5703 ++it)
5704 {
5705 pMedium = *it;
5706 aChildrenToReparent->Append(pMedium, true /* fLockWrite */);
5707 }
5708 if (fLockMedia && aChildrenToReparent)
5709 {
5710 treeLock.release();
5711 rc = aChildrenToReparent->Lock();
5712 treeLock.acquire();
5713 if (FAILED(rc))
5714 throw rc;
5715 }
5716 }
5717 for (pLast = pLastIntermediate;
5718 !pLast.isNull() && pLast != pTarget && pLast != this;
5719 pLast = pLast->i_getParent())
5720 {
5721 AutoWriteLock alock(pLast COMMA_LOCKVAL_SRC_POS);
5722 if (pLast->m->state == MediumState_Created)
5723 {
5724 rc = pLast->i_markForDeletion();
5725 if (FAILED(rc))
5726 throw rc;
5727 }
5728 else
5729 throw pLast->i_setStateError();
5730 }
5731
5732 /* Tweak the lock list in the backward merge case, as the target
5733 * isn't marked to be locked for writing yet. */
5734 if (!fMergeForward)
5735 {
5736 MediumLockList::Base::iterator lockListBegin =
5737 aMediumLockList->GetBegin();
5738 MediumLockList::Base::iterator lockListEnd =
5739 aMediumLockList->GetEnd();
5740 ++lockListEnd;
5741 for (MediumLockList::Base::iterator it = lockListBegin;
5742 it != lockListEnd;
5743 ++it)
5744 {
5745 MediumLock &mediumLock = *it;
5746 if (mediumLock.GetMedium() == pTarget)
5747 {
5748 HRESULT rc2 = mediumLock.UpdateLock(true);
5749 AssertComRC(rc2);
5750 break;
5751 }
5752 }
5753 }
5754
5755 if (fLockMedia)
5756 {
5757 treeLock.release();
5758 rc = aMediumLockList->Lock();
5759 treeLock.acquire();
5760 if (FAILED(rc))
5761 {
5762 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
5763 throw setError(rc,
5764 tr("Failed to lock media when merging to '%s'"),
5765 pTarget->i_getLocationFull().c_str());
5766 }
5767 }
5768 }
5769 catch (HRESULT aRC) { rc = aRC; }
5770
5771 if (FAILED(rc))
5772 {
5773 if (aMediumLockList)
5774 {
5775 delete aMediumLockList;
5776 aMediumLockList = NULL;
5777 }
5778 if (aChildrenToReparent)
5779 {
5780 delete aChildrenToReparent;
5781 aChildrenToReparent = NULL;
5782 }
5783 }
5784
5785 return rc;
5786}
5787
5788/**
5789 * Merges this medium to the specified medium which must be either its
5790 * direct ancestor or descendant.
5791 *
5792 * Given this medium is SOURCE and the specified medium is TARGET, we will
5793 * get two variants of the merge operation:
5794 *
5795 * forward merge
5796 * ------------------------->
5797 * [Extra] <- SOURCE <- Intermediate <- TARGET
5798 * Any Del Del LockWr
5799 *
5800 *
5801 * backward merge
5802 * <-------------------------
5803 * TARGET <- Intermediate <- SOURCE <- [Extra]
5804 * LockWr Del Del LockWr
5805 *
5806 * Each diagram shows the involved media on the media chain where
5807 * SOURCE and TARGET belong. Under each medium there is a state value which
5808 * the medium must have at a time of the mergeTo() call.
5809 *
5810 * The media in the square braces may be absent (e.g. when the forward
5811 * operation takes place and SOURCE is the base medium, or when the backward
5812 * merge operation takes place and TARGET is the last child in the chain) but if
5813 * they present they are involved too as shown.
5814 *
5815 * Neither the source medium nor intermediate media may be attached to
5816 * any VM directly or in the snapshot, otherwise this method will assert.
5817 *
5818 * The #i_prepareMergeTo() method must be called prior to this method to place
5819 * all involved to necessary states and perform other consistency checks.
5820 *
5821 * If @a aWait is @c true then this method will perform the operation on the
5822 * calling thread and will not return to the caller until the operation is
5823 * completed. When this method succeeds, all intermediate medium objects in
5824 * the chain will be uninitialized, the state of the target medium (and all
5825 * involved extra media) will be restored. @a aMediumLockList will not be
5826 * deleted, whether the operation is successful or not. The caller has to do
5827 * this if appropriate. Note that this (source) medium is not uninitialized
5828 * because of possible AutoCaller instances held by the caller of this method
5829 * on the current thread. It's therefore the responsibility of the caller to
5830 * call Medium::uninit() after releasing all callers.
5831 *
5832 * If @a aWait is @c false then this method will create a thread to perform the
5833 * operation asynchronously and will return immediately. If the operation
5834 * succeeds, the thread will uninitialize the source medium object and all
5835 * intermediate medium objects in the chain, reset the state of the target
5836 * medium (and all involved extra media) and delete @a aMediumLockList.
5837 * If the operation fails, the thread will only reset the states of all
5838 * involved media and delete @a aMediumLockList.
5839 *
5840 * When this method fails (regardless of the @a aWait mode), it is a caller's
5841 * responsibility to undo state changes and delete @a aMediumLockList using
5842 * #i_cancelMergeTo().
5843 *
5844 * If @a aProgress is not NULL but the object it points to is @c null then a new
5845 * progress object will be created and assigned to @a *aProgress on success,
5846 * otherwise the existing progress object is used. If Progress is NULL, then no
5847 * progress object is created/used at all. Note that @a aProgress cannot be
5848 * NULL when @a aWait is @c false (this method will assert in this case).
5849 *
5850 * @param pTarget Target medium.
5851 * @param fMergeForward Merge direction.
5852 * @param pParentForTarget New parent for target medium after merge.
5853 * @param aChildrenToReparent List of children of the source which will have
5854 * to be reparented to the target after merge.
5855 * @param aMediumLockList Medium locking information.
5856 * @param aProgress Where to find/store a Progress object to track operation
5857 * completion.
5858 * @param aWait @c true if this method should block instead of creating
5859 * an asynchronous thread.
5860 *
5861 * @note Locks the tree lock for writing. Locks the media from the chain
5862 * for writing.
5863 */
5864HRESULT Medium::i_mergeTo(const ComObjPtr<Medium> &pTarget,
5865 bool fMergeForward,
5866 const ComObjPtr<Medium> &pParentForTarget,
5867 MediumLockList *aChildrenToReparent,
5868 MediumLockList *aMediumLockList,
5869 ComObjPtr<Progress> *aProgress,
5870 bool aWait)
5871{
5872 AssertReturn(pTarget != NULL, E_FAIL);
5873 AssertReturn(pTarget != this, E_FAIL);
5874 AssertReturn(aMediumLockList != NULL, E_FAIL);
5875 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
5876
5877 AutoCaller autoCaller(this);
5878 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5879
5880 AutoCaller targetCaller(pTarget);
5881 AssertComRCReturnRC(targetCaller.rc());
5882
5883 HRESULT rc = S_OK;
5884 ComObjPtr<Progress> pProgress;
5885 Medium::Task *pTask = NULL;
5886
5887 try
5888 {
5889 if (aProgress != NULL)
5890 {
5891 /* use the existing progress object... */
5892 pProgress = *aProgress;
5893
5894 /* ...but create a new one if it is null */
5895 if (pProgress.isNull())
5896 {
5897 Utf8Str tgtName;
5898 {
5899 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
5900 tgtName = pTarget->i_getName();
5901 }
5902
5903 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
5904
5905 pProgress.createObject();
5906 rc = pProgress->init(m->pVirtualBox,
5907 static_cast<IMedium*>(this),
5908 BstrFmt(tr("Merging medium '%s' to '%s'"),
5909 i_getName().c_str(),
5910 tgtName.c_str()).raw(),
5911 TRUE /* aCancelable */);
5912 if (FAILED(rc))
5913 throw rc;
5914 }
5915 }
5916
5917 /* setup task object to carry out the operation sync/async */
5918 pTask = new Medium::MergeTask(this, pTarget, fMergeForward,
5919 pParentForTarget, aChildrenToReparent,
5920 pProgress, aMediumLockList,
5921 aWait /* fKeepMediumLockList */);
5922 rc = pTask->rc();
5923 AssertComRC(rc);
5924 if (FAILED(rc))
5925 throw rc;
5926 }
5927 catch (HRESULT aRC) { rc = aRC; }
5928
5929 if (SUCCEEDED(rc))
5930 {
5931 if (aWait)
5932 {
5933 rc = pTask->runNow();
5934
5935 delete pTask;
5936 }
5937 else
5938 rc = pTask->createThread();
5939
5940 if (SUCCEEDED(rc) && aProgress != NULL)
5941 *aProgress = pProgress;
5942 }
5943 else if (pTask != NULL)
5944 delete pTask;
5945
5946 return rc;
5947}
5948
5949/**
5950 * Undoes what #i_prepareMergeTo() did. Must be called if #mergeTo() is not
5951 * called or fails. Frees memory occupied by @a aMediumLockList and unlocks
5952 * the medium objects in @a aChildrenToReparent.
5953 *
5954 * @param aChildrenToReparent List of children of the source which will have
5955 * to be reparented to the target after merge.
5956 * @param aMediumLockList Medium locking information.
5957 *
5958 * @note Locks the media from the chain for writing.
5959 */
5960void Medium::i_cancelMergeTo(MediumLockList *aChildrenToReparent,
5961 MediumLockList *aMediumLockList)
5962{
5963 AutoCaller autoCaller(this);
5964 AssertComRCReturnVoid(autoCaller.rc());
5965
5966 AssertReturnVoid(aMediumLockList != NULL);
5967
5968 /* Revert media marked for deletion to previous state. */
5969 HRESULT rc;
5970 MediumLockList::Base::const_iterator mediumListBegin =
5971 aMediumLockList->GetBegin();
5972 MediumLockList::Base::const_iterator mediumListEnd =
5973 aMediumLockList->GetEnd();
5974 for (MediumLockList::Base::const_iterator it = mediumListBegin;
5975 it != mediumListEnd;
5976 ++it)
5977 {
5978 const MediumLock &mediumLock = *it;
5979 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
5980 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
5981
5982 if (pMedium->m->state == MediumState_Deleting)
5983 {
5984 rc = pMedium->i_unmarkForDeletion();
5985 AssertComRC(rc);
5986 }
5987 else if ( ( pMedium->m->state == MediumState_LockedWrite
5988 || pMedium->m->state == MediumState_LockedRead)
5989 && pMedium->m->preLockState == MediumState_Deleting)
5990 {
5991 rc = pMedium->i_unmarkLockedForDeletion();
5992 AssertComRC(rc);
5993 }
5994 }
5995
5996 /* the destructor will do the work */
5997 delete aMediumLockList;
5998
5999 /* unlock the children which had to be reparented, the destructor will do
6000 * the work */
6001 if (aChildrenToReparent)
6002 delete aChildrenToReparent;
6003}
6004
6005/**
6006 * Fix the parent UUID of all children to point to this medium as their
6007 * parent.
6008 */
6009HRESULT Medium::i_fixParentUuidOfChildren(MediumLockList *pChildrenToReparent)
6010{
6011 /** @todo r=klaus The code below needs to be double checked with regard
6012 * to lock order violations, it probably causes lock order issues related
6013 * to the AutoCaller usage. Likewise the code using this method seems
6014 * problematic. */
6015 Assert(!isWriteLockOnCurrentThread());
6016 Assert(!m->pVirtualBox->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
6017 MediumLockList mediumLockList;
6018 HRESULT rc = i_createMediumLockList(true /* fFailIfInaccessible */,
6019 NULL /* pToLockWrite */,
6020 false /* fMediumLockWriteAll */,
6021 this,
6022 mediumLockList);
6023 AssertComRCReturnRC(rc);
6024
6025 try
6026 {
6027 PVDISK hdd;
6028 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
6029 ComAssertRCThrow(vrc, E_FAIL);
6030
6031 try
6032 {
6033 MediumLockList::Base::iterator lockListBegin =
6034 mediumLockList.GetBegin();
6035 MediumLockList::Base::iterator lockListEnd =
6036 mediumLockList.GetEnd();
6037 for (MediumLockList::Base::iterator it = lockListBegin;
6038 it != lockListEnd;
6039 ++it)
6040 {
6041 MediumLock &mediumLock = *it;
6042 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6043 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6044
6045 // open the medium
6046 vrc = VDOpen(hdd,
6047 pMedium->m->strFormat.c_str(),
6048 pMedium->m->strLocationFull.c_str(),
6049 VD_OPEN_FLAGS_READONLY | m->uOpenFlagsDef,
6050 pMedium->m->vdImageIfaces);
6051 if (RT_FAILURE(vrc))
6052 throw vrc;
6053 }
6054
6055 MediumLockList::Base::iterator childrenBegin = pChildrenToReparent->GetBegin();
6056 MediumLockList::Base::iterator childrenEnd = pChildrenToReparent->GetEnd();
6057 for (MediumLockList::Base::iterator it = childrenBegin;
6058 it != childrenEnd;
6059 ++it)
6060 {
6061 Medium *pMedium = it->GetMedium();
6062 /* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
6063 vrc = VDOpen(hdd,
6064 pMedium->m->strFormat.c_str(),
6065 pMedium->m->strLocationFull.c_str(),
6066 VD_OPEN_FLAGS_INFO | m->uOpenFlagsDef,
6067 pMedium->m->vdImageIfaces);
6068 if (RT_FAILURE(vrc))
6069 throw vrc;
6070
6071 vrc = VDSetParentUuid(hdd, VD_LAST_IMAGE, m->id.raw());
6072 if (RT_FAILURE(vrc))
6073 throw vrc;
6074
6075 vrc = VDClose(hdd, false /* fDelete */);
6076 if (RT_FAILURE(vrc))
6077 throw vrc;
6078 }
6079 }
6080 catch (HRESULT aRC) { rc = aRC; }
6081 catch (int aVRC)
6082 {
6083 rc = setError(E_FAIL,
6084 tr("Could not update medium UUID references to parent '%s' (%s)"),
6085 m->strLocationFull.c_str(),
6086 i_vdError(aVRC).c_str());
6087 }
6088
6089 VDDestroy(hdd);
6090 }
6091 catch (HRESULT aRC) { rc = aRC; }
6092
6093 return rc;
6094}
6095
6096/**
6097 *
6098 * @note Similar code exists in i_taskExportHandler.
6099 */
6100HRESULT Medium::i_addRawToFss(const char *aFilename, SecretKeyStore *pKeyStore, RTVFSFSSTREAM hVfsFssDst,
6101 const ComObjPtr<Progress> &aProgress, bool fSparse)
6102{
6103 AutoCaller autoCaller(this);
6104 HRESULT hrc = autoCaller.rc();
6105 if (SUCCEEDED(hrc))
6106 {
6107 /*
6108 * Get a readonly hdd for this medium.
6109 */
6110 Medium::CryptoFilterSettings CryptoSettingsRead;
6111 MediumLockList SourceMediumLockList;
6112 PVDISK pHdd;
6113 hrc = i_openHddForReading(pKeyStore, &pHdd, &SourceMediumLockList, &CryptoSettingsRead);
6114 if (SUCCEEDED(hrc))
6115 {
6116 /*
6117 * Create a VFS file interface to the HDD and attach a progress wrapper
6118 * that monitors the progress reading of the raw image. The image will
6119 * be read twice if hVfsFssDst does sparse processing.
6120 */
6121 RTVFSFILE hVfsFileDisk = NIL_RTVFSFILE;
6122 int vrc = VDCreateVfsFileFromDisk(pHdd, 0 /*fFlags*/, &hVfsFileDisk);
6123 if (RT_SUCCESS(vrc))
6124 {
6125 RTVFSFILE hVfsFileProgress = NIL_RTVFSFILE;
6126 vrc = RTVfsCreateProgressForFile(hVfsFileDisk, aProgress->i_iprtProgressCallback, &*aProgress,
6127 RTVFSPROGRESS_F_CANCELABLE | RTVFSPROGRESS_F_FORWARD_SEEK_AS_READ,
6128 VDGetSize(pHdd, VD_LAST_IMAGE) * (fSparse ? 2 : 1) /*cbExpectedRead*/,
6129 0 /*cbExpectedWritten*/, &hVfsFileProgress);
6130 RTVfsFileRelease(hVfsFileDisk);
6131 if (RT_SUCCESS(vrc))
6132 {
6133 RTVFSOBJ hVfsObj = RTVfsObjFromFile(hVfsFileProgress);
6134 RTVfsFileRelease(hVfsFileProgress);
6135
6136 vrc = RTVfsFsStrmAdd(hVfsFssDst, aFilename, hVfsObj, 0 /*fFlags*/);
6137 RTVfsObjRelease(hVfsObj);
6138 if (RT_FAILURE(vrc))
6139 hrc = setErrorBoth(VBOX_E_FILE_ERROR, vrc, tr("Failed to add '%s' to output (%Rrc)"), aFilename, vrc);
6140 }
6141 else
6142 hrc = setErrorBoth(VBOX_E_FILE_ERROR, vrc,
6143 tr("RTVfsCreateProgressForFile failed when processing '%s' (%Rrc)"), aFilename, vrc);
6144 }
6145 else
6146 hrc = setErrorBoth(VBOX_E_FILE_ERROR, vrc, tr("VDCreateVfsFileFromDisk failed for '%s' (%Rrc)"), aFilename, vrc);
6147 VDDestroy(pHdd);
6148 }
6149 }
6150 return hrc;
6151}
6152
6153/**
6154 * Used by IAppliance to export disk images.
6155 *
6156 * @param aFilename Filename to create (UTF8).
6157 * @param aFormat Medium format for creating @a aFilename.
6158 * @param aVariant Which exact image format variant to use for the
6159 * destination image.
6160 * @param pKeyStore The optional key store for decrypting the data for
6161 * encrypted media during the export.
6162 * @param aVDImageIOIf Pointer to the callback table for a VDINTERFACEIO
6163 * interface. May be NULL.
6164 * @param aVDImageIOUser Opaque data for the callbacks.
6165 * @param aProgress Progress object to use.
6166 * @return
6167 * @note The source format is defined by the Medium instance.
6168 *
6169 * @todo The only consumer of this method (Appliance::i_writeFSImpl) is already
6170 * on a worker thread, so perhaps consider bypassing the thread here and
6171 * run in the task synchronously? VBoxSVC has enough threads as it is...
6172 */
6173HRESULT Medium::i_exportFile(const char *aFilename,
6174 const ComObjPtr<MediumFormat> &aFormat,
6175 MediumVariant_T aVariant,
6176 SecretKeyStore *pKeyStore,
6177#ifdef VBOX_WITH_NEW_TAR_CREATOR
6178 RTVFSIOSTREAM hVfsIosDst,
6179#else
6180 PVDINTERFACEIO aVDImageIOIf, void *aVDImageIOUser,
6181#endif
6182 const ComObjPtr<Progress> &aProgress)
6183{
6184 AssertPtrReturn(aFilename, E_INVALIDARG);
6185 AssertReturn(aFormat.isNotNull(), E_INVALIDARG);
6186 AssertReturn(aProgress.isNotNull(), E_INVALIDARG);
6187
6188 AutoCaller autoCaller(this);
6189 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6190
6191 HRESULT rc = S_OK;
6192 Medium::Task *pTask = NULL;
6193
6194 try
6195 {
6196 // This needs no extra locks besides what is done in the called methods.
6197
6198 /* Build the source lock list. */
6199 MediumLockList *pSourceMediumLockList(new MediumLockList());
6200 rc = i_createMediumLockList(true /* fFailIfInaccessible */,
6201 NULL /* pToLockWrite */,
6202 false /* fMediumLockWriteAll */,
6203 NULL,
6204 *pSourceMediumLockList);
6205 if (FAILED(rc))
6206 {
6207 delete pSourceMediumLockList;
6208 throw rc;
6209 }
6210
6211 rc = pSourceMediumLockList->Lock();
6212 if (FAILED(rc))
6213 {
6214 delete pSourceMediumLockList;
6215 throw setError(rc,
6216 tr("Failed to lock source media '%s'"),
6217 i_getLocationFull().c_str());
6218 }
6219
6220 /* setup task object to carry out the operation asynchronously */
6221 pTask = new Medium::ExportTask(this, aProgress, aFilename, aFormat, aVariant,
6222#ifdef VBOX_WITH_NEW_TAR_CREATOR
6223 pKeyStore, hVfsIosDst, pSourceMediumLockList);
6224#else
6225 pKeyStore, aVDImageIOIf, aVDImageIOUser, pSourceMediumLockList);
6226#endif
6227 rc = pTask->rc();
6228 AssertComRC(rc);
6229 if (FAILED(rc))
6230 throw rc;
6231 }
6232 catch (HRESULT aRC) { rc = aRC; }
6233
6234 if (SUCCEEDED(rc))
6235 rc = pTask->createThread();
6236 else if (pTask != NULL)
6237 delete pTask;
6238
6239 return rc;
6240}
6241
6242/**
6243 * Used by IAppliance to import disk images.
6244 *
6245 * @param aFilename Filename to read (UTF8).
6246 * @param aFormat Medium format for reading @a aFilename.
6247 * @param aVariant Which exact image format variant to use
6248 * for the destination image.
6249 * @param aVfsIosSrc Handle to the source I/O stream.
6250 * @param aParent Parent medium. May be NULL.
6251 * @param aProgress Progress object to use.
6252 * @return
6253 * @note The destination format is defined by the Medium instance.
6254 *
6255 * @todo The only consumer of this method (Appliance::i_importOneDiskImage) is
6256 * already on a worker thread, so perhaps consider bypassing the thread
6257 * here and run in the task synchronously? VBoxSVC has enough threads as
6258 * it is...
6259 */
6260HRESULT Medium::i_importFile(const char *aFilename,
6261 const ComObjPtr<MediumFormat> &aFormat,
6262 MediumVariant_T aVariant,
6263 RTVFSIOSTREAM aVfsIosSrc,
6264 const ComObjPtr<Medium> &aParent,
6265 const ComObjPtr<Progress> &aProgress)
6266{
6267 /** @todo r=klaus The code below needs to be double checked with regard
6268 * to lock order violations, it probably causes lock order issues related
6269 * to the AutoCaller usage. */
6270 AssertPtrReturn(aFilename, E_INVALIDARG);
6271 AssertReturn(!aFormat.isNull(), E_INVALIDARG);
6272 AssertReturn(!aProgress.isNull(), E_INVALIDARG);
6273
6274 AutoCaller autoCaller(this);
6275 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6276
6277 HRESULT rc = S_OK;
6278 Medium::Task *pTask = NULL;
6279
6280 try
6281 {
6282 // locking: we need the tree lock first because we access parent pointers
6283 // and we need to write-lock the media involved
6284 uint32_t cHandles = 2;
6285 LockHandle* pHandles[3] = { &m->pVirtualBox->i_getMediaTreeLockHandle(),
6286 this->lockHandle() };
6287 /* Only add parent to the lock if it is not null */
6288 if (!aParent.isNull())
6289 pHandles[cHandles++] = aParent->lockHandle();
6290 AutoWriteLock alock(cHandles,
6291 pHandles
6292 COMMA_LOCKVAL_SRC_POS);
6293
6294 if ( m->state != MediumState_NotCreated
6295 && m->state != MediumState_Created)
6296 throw i_setStateError();
6297
6298 /* Build the target lock list. */
6299 MediumLockList *pTargetMediumLockList(new MediumLockList());
6300 alock.release();
6301 rc = i_createMediumLockList(true /* fFailIfInaccessible */,
6302 this /* pToLockWrite */,
6303 false /* fMediumLockWriteAll */,
6304 aParent,
6305 *pTargetMediumLockList);
6306 alock.acquire();
6307 if (FAILED(rc))
6308 {
6309 delete pTargetMediumLockList;
6310 throw rc;
6311 }
6312
6313 alock.release();
6314 rc = pTargetMediumLockList->Lock();
6315 alock.acquire();
6316 if (FAILED(rc))
6317 {
6318 delete pTargetMediumLockList;
6319 throw setError(rc,
6320 tr("Failed to lock target media '%s'"),
6321 i_getLocationFull().c_str());
6322 }
6323
6324 /* setup task object to carry out the operation asynchronously */
6325 pTask = new Medium::ImportTask(this, aProgress, aFilename, aFormat, aVariant,
6326 aVfsIosSrc, aParent, pTargetMediumLockList);
6327 rc = pTask->rc();
6328 AssertComRC(rc);
6329 if (FAILED(rc))
6330 throw rc;
6331
6332 if (m->state == MediumState_NotCreated)
6333 m->state = MediumState_Creating;
6334 }
6335 catch (HRESULT aRC) { rc = aRC; }
6336
6337 if (SUCCEEDED(rc))
6338 rc = pTask->createThread();
6339 else if (pTask != NULL)
6340 delete pTask;
6341
6342 return rc;
6343}
6344
6345/**
6346 * Internal version of the public CloneTo API which allows to enable certain
6347 * optimizations to improve speed during VM cloning.
6348 *
6349 * @param aTarget Target medium
6350 * @param aVariant Which exact image format variant to use
6351 * for the destination image.
6352 * @param aParent Parent medium. May be NULL.
6353 * @param aProgress Progress object to use.
6354 * @param idxSrcImageSame The last image in the source chain which has the
6355 * same content as the given image in the destination
6356 * chain. Use UINT32_MAX to disable this optimization.
6357 * @param idxDstImageSame The last image in the destination chain which has the
6358 * same content as the given image in the source chain.
6359 * Use UINT32_MAX to disable this optimization.
6360 * @return
6361 */
6362HRESULT Medium::i_cloneToEx(const ComObjPtr<Medium> &aTarget, ULONG aVariant,
6363 const ComObjPtr<Medium> &aParent, IProgress **aProgress,
6364 uint32_t idxSrcImageSame, uint32_t idxDstImageSame)
6365{
6366 /** @todo r=klaus The code below needs to be double checked with regard
6367 * to lock order violations, it probably causes lock order issues related
6368 * to the AutoCaller usage. */
6369 CheckComArgNotNull(aTarget);
6370 CheckComArgOutPointerValid(aProgress);
6371 ComAssertRet(aTarget != this, E_INVALIDARG);
6372
6373 AutoCaller autoCaller(this);
6374 if (FAILED(autoCaller.rc())) return autoCaller.rc();
6375
6376 HRESULT rc = S_OK;
6377 ComObjPtr<Progress> pProgress;
6378 Medium::Task *pTask = NULL;
6379
6380 try
6381 {
6382 // locking: we need the tree lock first because we access parent pointers
6383 // and we need to write-lock the media involved
6384 uint32_t cHandles = 3;
6385 LockHandle* pHandles[4] = { &m->pVirtualBox->i_getMediaTreeLockHandle(),
6386 this->lockHandle(),
6387 aTarget->lockHandle() };
6388 /* Only add parent to the lock if it is not null */
6389 if (!aParent.isNull())
6390 pHandles[cHandles++] = aParent->lockHandle();
6391 AutoWriteLock alock(cHandles,
6392 pHandles
6393 COMMA_LOCKVAL_SRC_POS);
6394
6395 if ( aTarget->m->state != MediumState_NotCreated
6396 && aTarget->m->state != MediumState_Created)
6397 throw aTarget->i_setStateError();
6398
6399 /* Build the source lock list. */
6400 MediumLockList *pSourceMediumLockList(new MediumLockList());
6401 alock.release();
6402 rc = i_createMediumLockList(true /* fFailIfInaccessible */,
6403 NULL /* pToLockWrite */,
6404 false /* fMediumLockWriteAll */,
6405 NULL,
6406 *pSourceMediumLockList);
6407 alock.acquire();
6408 if (FAILED(rc))
6409 {
6410 delete pSourceMediumLockList;
6411 throw rc;
6412 }
6413
6414 /* Build the target lock list (including the to-be parent chain). */
6415 MediumLockList *pTargetMediumLockList(new MediumLockList());
6416 alock.release();
6417 rc = aTarget->i_createMediumLockList(true /* fFailIfInaccessible */,
6418 aTarget /* pToLockWrite */,
6419 false /* fMediumLockWriteAll */,
6420 aParent,
6421 *pTargetMediumLockList);
6422 alock.acquire();
6423 if (FAILED(rc))
6424 {
6425 delete pSourceMediumLockList;
6426 delete pTargetMediumLockList;
6427 throw rc;
6428 }
6429
6430 alock.release();
6431 rc = pSourceMediumLockList->Lock();
6432 alock.acquire();
6433 if (FAILED(rc))
6434 {
6435 delete pSourceMediumLockList;
6436 delete pTargetMediumLockList;
6437 throw setError(rc,
6438 tr("Failed to lock source media '%s'"),
6439 i_getLocationFull().c_str());
6440 }
6441 alock.release();
6442 rc = pTargetMediumLockList->Lock();
6443 alock.acquire();
6444 if (FAILED(rc))
6445 {
6446 delete pSourceMediumLockList;
6447 delete pTargetMediumLockList;
6448 throw setError(rc,
6449 tr("Failed to lock target media '%s'"),
6450 aTarget->i_getLocationFull().c_str());
6451 }
6452
6453 pProgress.createObject();
6454 rc = pProgress->init(m->pVirtualBox,
6455 static_cast <IMedium *>(this),
6456 BstrFmt(tr("Creating clone medium '%s'"), aTarget->m->strLocationFull.c_str()).raw(),
6457 TRUE /* aCancelable */);
6458 if (FAILED(rc))
6459 {
6460 delete pSourceMediumLockList;
6461 delete pTargetMediumLockList;
6462 throw rc;
6463 }
6464
6465 /* setup task object to carry out the operation asynchronously */
6466 pTask = new Medium::CloneTask(this, pProgress, aTarget,
6467 (MediumVariant_T)aVariant,
6468 aParent, idxSrcImageSame,
6469 idxDstImageSame, pSourceMediumLockList,
6470 pTargetMediumLockList);
6471 rc = pTask->rc();
6472 AssertComRC(rc);
6473 if (FAILED(rc))
6474 throw rc;
6475
6476 if (aTarget->m->state == MediumState_NotCreated)
6477 aTarget->m->state = MediumState_Creating;
6478 }
6479 catch (HRESULT aRC) { rc = aRC; }
6480
6481 if (SUCCEEDED(rc))
6482 {
6483 rc = pTask->createThread();
6484
6485 if (SUCCEEDED(rc))
6486 pProgress.queryInterfaceTo(aProgress);
6487 }
6488 else if (pTask != NULL)
6489 delete pTask;
6490
6491 return rc;
6492}
6493
6494/**
6495 * Returns the key identifier for this medium if encryption is configured.
6496 *
6497 * @returns Key identifier or empty string if no encryption is configured.
6498 */
6499const Utf8Str& Medium::i_getKeyId()
6500{
6501 ComObjPtr<Medium> pBase = i_getBase();
6502
6503 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
6504
6505 settings::StringsMap::const_iterator it = pBase->m->mapProperties.find("CRYPT/KeyId");
6506 if (it == pBase->m->mapProperties.end())
6507 return Utf8Str::Empty;
6508
6509 return it->second;
6510}
6511
6512/**
6513 * Returns all filter related properties.
6514 *
6515 * @returns COM status code.
6516 * @param aReturnNames Where to store the properties names on success.
6517 * @param aReturnValues Where to store the properties values on success.
6518 */
6519HRESULT Medium::i_getFilterProperties(std::vector<com::Utf8Str> &aReturnNames,
6520 std::vector<com::Utf8Str> &aReturnValues)
6521{
6522 std::vector<com::Utf8Str> aPropNames;
6523 std::vector<com::Utf8Str> aPropValues;
6524 HRESULT hrc = getProperties(Utf8Str(""), aPropNames, aPropValues);
6525
6526 if (SUCCEEDED(hrc))
6527 {
6528 unsigned cReturnSize = 0;
6529 aReturnNames.resize(0);
6530 aReturnValues.resize(0);
6531 for (unsigned idx = 0; idx < aPropNames.size(); idx++)
6532 {
6533 if (i_isPropertyForFilter(aPropNames[idx]))
6534 {
6535 aReturnNames.resize(cReturnSize + 1);
6536 aReturnValues.resize(cReturnSize + 1);
6537 aReturnNames[cReturnSize] = aPropNames[idx];
6538 aReturnValues[cReturnSize] = aPropValues[idx];
6539 cReturnSize++;
6540 }
6541 }
6542 }
6543
6544 return hrc;
6545}
6546
6547/**
6548 * Preparation to move this medium to a new location
6549 *
6550 * @param aLocation Location of the storage unit. If the location is a FS-path,
6551 * then it can be relative to the VirtualBox home directory.
6552 *
6553 * @note Must be called from under this object's write lock.
6554 */
6555HRESULT Medium::i_preparationForMoving(const Utf8Str &aLocation)
6556{
6557 HRESULT rc = E_FAIL;
6558
6559 if (i_getLocationFull() != aLocation)
6560 {
6561 m->strNewLocationFull = aLocation;
6562 m->fMoveThisMedium = true;
6563 rc = S_OK;
6564 }
6565
6566 return rc;
6567}
6568
6569/**
6570 * Checking whether current operation "moving" or not
6571 */
6572bool Medium::i_isMoveOperation(const ComObjPtr<Medium> &aTarget) const
6573{
6574 RT_NOREF(aTarget);
6575 return (m->fMoveThisMedium == true) ? true:false;
6576}
6577
6578bool Medium::i_resetMoveOperationData()
6579{
6580 m->strNewLocationFull.setNull();
6581 m->fMoveThisMedium = false;
6582 return true;
6583}
6584
6585Utf8Str Medium::i_getNewLocationForMoving() const
6586{
6587 if (m->fMoveThisMedium == true)
6588 return m->strNewLocationFull;
6589 else
6590 return Utf8Str();
6591}
6592////////////////////////////////////////////////////////////////////////////////
6593//
6594// Private methods
6595//
6596////////////////////////////////////////////////////////////////////////////////
6597
6598/**
6599 * Queries information from the medium.
6600 *
6601 * As a result of this call, the accessibility state and data members such as
6602 * size and description will be updated with the current information.
6603 *
6604 * @note This method may block during a system I/O call that checks storage
6605 * accessibility.
6606 *
6607 * @note Caller MUST NOT hold the media tree or medium lock.
6608 *
6609 * @note Locks m->pParent for reading. Locks this object for writing.
6610 *
6611 * @param fSetImageId Whether to reset the UUID contained in the image file
6612 * to the UUID in the medium instance data (see SetIDs())
6613 * @param fSetParentId Whether to reset the parent UUID contained in the image
6614 * file to the parent UUID in the medium instance data (see
6615 * SetIDs())
6616 * @param autoCaller
6617 * @return
6618 */
6619HRESULT Medium::i_queryInfo(bool fSetImageId, bool fSetParentId, AutoCaller &autoCaller)
6620{
6621 Assert(!isWriteLockOnCurrentThread());
6622 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
6623
6624 if ( ( m->state != MediumState_Created
6625 && m->state != MediumState_Inaccessible
6626 && m->state != MediumState_LockedRead)
6627 || m->fClosing)
6628 return E_FAIL;
6629
6630 HRESULT rc = S_OK;
6631
6632 int vrc = VINF_SUCCESS;
6633
6634 /* check if a blocking i_queryInfo() call is in progress on some other thread,
6635 * and wait for it to finish if so instead of querying data ourselves */
6636 if (m->queryInfoRunning)
6637 {
6638 Assert( m->state == MediumState_LockedRead
6639 || m->state == MediumState_LockedWrite);
6640
6641 while (m->queryInfoRunning)
6642 {
6643 alock.release();
6644 /* must not hold the object lock now */
6645 Assert(!isWriteLockOnCurrentThread());
6646 {
6647 AutoReadLock qlock(m->queryInfoSem COMMA_LOCKVAL_SRC_POS);
6648 }
6649 alock.acquire();
6650 }
6651
6652 return S_OK;
6653 }
6654
6655 bool success = false;
6656 Utf8Str lastAccessError;
6657
6658 /* are we dealing with a new medium constructed using the existing
6659 * location? */
6660 bool isImport = m->id.isZero();
6661 unsigned uOpenFlags = VD_OPEN_FLAGS_INFO;
6662
6663 /* Note that we don't use VD_OPEN_FLAGS_READONLY when opening new
6664 * media because that would prevent necessary modifications
6665 * when opening media of some third-party formats for the first
6666 * time in VirtualBox (such as VMDK for which VDOpen() needs to
6667 * generate an UUID if it is missing) */
6668 if ( m->hddOpenMode == OpenReadOnly
6669 || m->type == MediumType_Readonly
6670 || (!isImport && !fSetImageId && !fSetParentId)
6671 )
6672 uOpenFlags |= VD_OPEN_FLAGS_READONLY;
6673
6674 /* Open shareable medium with the appropriate flags */
6675 if (m->type == MediumType_Shareable)
6676 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
6677
6678 /* Lock the medium, which makes the behavior much more consistent, must be
6679 * done before dropping the object lock and setting queryInfoRunning. */
6680 ComPtr<IToken> pToken;
6681 if (uOpenFlags & (VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_SHAREABLE))
6682 rc = LockRead(pToken.asOutParam());
6683 else
6684 rc = LockWrite(pToken.asOutParam());
6685 if (FAILED(rc)) return rc;
6686
6687 /* Copies of the input state fields which are not read-only,
6688 * as we're dropping the lock. CAUTION: be extremely careful what
6689 * you do with the contents of this medium object, as you will
6690 * create races if there are concurrent changes. */
6691 Utf8Str format(m->strFormat);
6692 Utf8Str location(m->strLocationFull);
6693 ComObjPtr<MediumFormat> formatObj = m->formatObj;
6694
6695 /* "Output" values which can't be set because the lock isn't held
6696 * at the time the values are determined. */
6697 Guid mediumId = m->id;
6698 uint64_t mediumSize = 0;
6699 uint64_t mediumLogicalSize = 0;
6700
6701 /* Flag whether a base image has a non-zero parent UUID and thus
6702 * need repairing after it was closed again. */
6703 bool fRepairImageZeroParentUuid = false;
6704
6705 ComObjPtr<VirtualBox> pVirtualBox = m->pVirtualBox;
6706
6707 /* must be set before leaving the object lock the first time */
6708 m->queryInfoRunning = true;
6709
6710 /* must leave object lock now, because a lock from a higher lock class
6711 * is needed and also a lengthy operation is coming */
6712 alock.release();
6713 autoCaller.release();
6714
6715 /* Note that taking the queryInfoSem after leaving the object lock above
6716 * can lead to short spinning of the loops waiting for i_queryInfo() to
6717 * complete. This is unavoidable since the other order causes a lock order
6718 * violation: here it would be requesting the object lock (at the beginning
6719 * of the method), then queryInfoSem, and below the other way round. */
6720 AutoWriteLock qlock(m->queryInfoSem COMMA_LOCKVAL_SRC_POS);
6721
6722 /* take the opportunity to have a media tree lock, released initially */
6723 Assert(!isWriteLockOnCurrentThread());
6724 Assert(!pVirtualBox->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
6725 AutoWriteLock treeLock(pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
6726 treeLock.release();
6727
6728 /* re-take the caller, but not the object lock, to keep uninit away */
6729 autoCaller.add();
6730 if (FAILED(autoCaller.rc()))
6731 {
6732 m->queryInfoRunning = false;
6733 return autoCaller.rc();
6734 }
6735
6736 try
6737 {
6738 /* skip accessibility checks for host drives */
6739 if (m->hostDrive)
6740 {
6741 success = true;
6742 throw S_OK;
6743 }
6744
6745 PVDISK hdd;
6746 vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
6747 ComAssertRCThrow(vrc, E_FAIL);
6748
6749 try
6750 {
6751 /** @todo This kind of opening of media is assuming that diff
6752 * media can be opened as base media. Should be documented that
6753 * it must work for all medium format backends. */
6754 vrc = VDOpen(hdd,
6755 format.c_str(),
6756 location.c_str(),
6757 uOpenFlags | m->uOpenFlagsDef,
6758 m->vdImageIfaces);
6759 if (RT_FAILURE(vrc))
6760 {
6761 lastAccessError = Utf8StrFmt(tr("Could not open the medium '%s'%s"),
6762 location.c_str(), i_vdError(vrc).c_str());
6763 throw S_OK;
6764 }
6765
6766 if (formatObj->i_getCapabilities() & MediumFormatCapabilities_Uuid)
6767 {
6768 /* Modify the UUIDs if necessary. The associated fields are
6769 * not modified by other code, so no need to copy. */
6770 if (fSetImageId)
6771 {
6772 alock.acquire();
6773 vrc = VDSetUuid(hdd, 0, m->uuidImage.raw());
6774 alock.release();
6775 if (RT_FAILURE(vrc))
6776 {
6777 lastAccessError = Utf8StrFmt(tr("Could not update the UUID of medium '%s'%s"),
6778 location.c_str(), i_vdError(vrc).c_str());
6779 throw S_OK;
6780 }
6781 mediumId = m->uuidImage;
6782 }
6783 if (fSetParentId)
6784 {
6785 alock.acquire();
6786 vrc = VDSetParentUuid(hdd, 0, m->uuidParentImage.raw());
6787 alock.release();
6788 if (RT_FAILURE(vrc))
6789 {
6790 lastAccessError = Utf8StrFmt(tr("Could not update the parent UUID of medium '%s'%s"),
6791 location.c_str(), i_vdError(vrc).c_str());
6792 throw S_OK;
6793 }
6794 }
6795 /* zap the information, these are no long-term members */
6796 alock.acquire();
6797 unconst(m->uuidImage).clear();
6798 unconst(m->uuidParentImage).clear();
6799 alock.release();
6800
6801 /* check the UUID */
6802 RTUUID uuid;
6803 vrc = VDGetUuid(hdd, 0, &uuid);
6804 ComAssertRCThrow(vrc, E_FAIL);
6805
6806 if (isImport)
6807 {
6808 mediumId = uuid;
6809
6810 if (mediumId.isZero() && (m->hddOpenMode == OpenReadOnly))
6811 // only when importing a VDMK that has no UUID, create one in memory
6812 mediumId.create();
6813 }
6814 else
6815 {
6816 Assert(!mediumId.isZero());
6817
6818 if (mediumId != uuid)
6819 {
6820 /** @todo r=klaus this always refers to VirtualBox.xml as the medium registry, even for new VMs */
6821 lastAccessError = Utf8StrFmt(
6822 tr("UUID {%RTuuid} of the medium '%s' does not match the value {%RTuuid} stored in the media registry ('%s')"),
6823 &uuid,
6824 location.c_str(),
6825 mediumId.raw(),
6826 pVirtualBox->i_settingsFilePath().c_str());
6827 throw S_OK;
6828 }
6829 }
6830 }
6831 else
6832 {
6833 /* the backend does not support storing UUIDs within the
6834 * underlying storage so use what we store in XML */
6835
6836 if (fSetImageId)
6837 {
6838 /* set the UUID if an API client wants to change it */
6839 alock.acquire();
6840 mediumId = m->uuidImage;
6841 alock.release();
6842 }
6843 else if (isImport)
6844 {
6845 /* generate an UUID for an imported UUID-less medium */
6846 mediumId.create();
6847 }
6848 }
6849
6850 /* set the image uuid before the below parent uuid handling code
6851 * might place it somewhere in the media tree, so that the medium
6852 * UUID is valid at this point */
6853 alock.acquire();
6854 if (isImport || fSetImageId)
6855 unconst(m->id) = mediumId;
6856 alock.release();
6857
6858 /* get the medium variant */
6859 unsigned uImageFlags;
6860 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
6861 ComAssertRCThrow(vrc, E_FAIL);
6862 alock.acquire();
6863 m->variant = (MediumVariant_T)uImageFlags;
6864 alock.release();
6865
6866 /* check/get the parent uuid and update corresponding state */
6867 if (uImageFlags & VD_IMAGE_FLAGS_DIFF)
6868 {
6869 RTUUID parentId;
6870 vrc = VDGetParentUuid(hdd, 0, &parentId);
6871 ComAssertRCThrow(vrc, E_FAIL);
6872
6873 /* streamOptimized VMDK images are only accepted as base
6874 * images, as this allows automatic repair of OVF appliances.
6875 * Since such images don't support random writes they will not
6876 * be created for diff images. Only an overly smart user might
6877 * manually create this case. Too bad for him. */
6878 if ( (isImport || fSetParentId)
6879 && !(uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
6880 {
6881 /* the parent must be known to us. Note that we freely
6882 * call locking methods of mVirtualBox and parent, as all
6883 * relevant locks must be already held. There may be no
6884 * concurrent access to the just opened medium on other
6885 * threads yet (and init() will fail if this method reports
6886 * MediumState_Inaccessible) */
6887
6888 ComObjPtr<Medium> pParent;
6889 if (RTUuidIsNull(&parentId))
6890 rc = VBOX_E_OBJECT_NOT_FOUND;
6891 else
6892 rc = pVirtualBox->i_findHardDiskById(Guid(parentId), false /* aSetError */, &pParent);
6893 if (FAILED(rc))
6894 {
6895 if (fSetImageId && !fSetParentId)
6896 {
6897 /* If the image UUID gets changed for an existing
6898 * image then the parent UUID can be stale. In such
6899 * cases clear the parent information. The parent
6900 * information may/will be re-set later if the
6901 * API client wants to adjust a complete medium
6902 * hierarchy one by one. */
6903 rc = S_OK;
6904 alock.acquire();
6905 RTUuidClear(&parentId);
6906 vrc = VDSetParentUuid(hdd, 0, &parentId);
6907 alock.release();
6908 ComAssertRCThrow(vrc, E_FAIL);
6909 }
6910 else
6911 {
6912 lastAccessError = Utf8StrFmt(tr("Parent medium with UUID {%RTuuid} of the medium '%s' is not found in the media registry ('%s')"),
6913 &parentId, location.c_str(),
6914 pVirtualBox->i_settingsFilePath().c_str());
6915 throw S_OK;
6916 }
6917 }
6918
6919 /* must drop the caller before taking the tree lock */
6920 autoCaller.release();
6921 /* we set m->pParent & children() */
6922 treeLock.acquire();
6923 autoCaller.add();
6924 if (FAILED(autoCaller.rc()))
6925 throw autoCaller.rc();
6926
6927 if (m->pParent)
6928 i_deparent();
6929
6930 if (!pParent.isNull())
6931 if (pParent->i_getDepth() >= SETTINGS_MEDIUM_DEPTH_MAX)
6932 {
6933 AutoReadLock plock(pParent COMMA_LOCKVAL_SRC_POS);
6934 throw setError(VBOX_E_INVALID_OBJECT_STATE,
6935 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"),
6936 pParent->m->strLocationFull.c_str());
6937 }
6938 i_setParent(pParent);
6939
6940 treeLock.release();
6941 }
6942 else
6943 {
6944 /* must drop the caller before taking the tree lock */
6945 autoCaller.release();
6946 /* we access m->pParent */
6947 treeLock.acquire();
6948 autoCaller.add();
6949 if (FAILED(autoCaller.rc()))
6950 throw autoCaller.rc();
6951
6952 /* check that parent UUIDs match. Note that there's no need
6953 * for the parent's AutoCaller (our lifetime is bound to
6954 * it) */
6955
6956 if (m->pParent.isNull())
6957 {
6958 /* Due to a bug in VDCopy() in VirtualBox 3.0.0-3.0.14
6959 * and 3.1.0-3.1.8 there are base images out there
6960 * which have a non-zero parent UUID. No point in
6961 * complaining about them, instead automatically
6962 * repair the problem. Later we can bring back the
6963 * error message, but we should wait until really
6964 * most users have repaired their images, either with
6965 * VBoxFixHdd or this way. */
6966#if 1
6967 fRepairImageZeroParentUuid = true;
6968#else /* 0 */
6969 lastAccessError = Utf8StrFmt(
6970 tr("Medium type of '%s' is differencing but it is not associated with any parent medium in the media registry ('%s')"),
6971 location.c_str(),
6972 pVirtualBox->settingsFilePath().c_str());
6973 treeLock.release();
6974 throw S_OK;
6975#endif /* 0 */
6976 }
6977
6978 {
6979 autoCaller.release();
6980 AutoReadLock parentLock(m->pParent COMMA_LOCKVAL_SRC_POS);
6981 autoCaller.add();
6982 if (FAILED(autoCaller.rc()))
6983 throw autoCaller.rc();
6984
6985 if ( !fRepairImageZeroParentUuid
6986 && m->pParent->i_getState() != MediumState_Inaccessible
6987 && m->pParent->i_getId() != parentId)
6988 {
6989 /** @todo r=klaus this always refers to VirtualBox.xml as the medium registry, even for new VMs */
6990 lastAccessError = Utf8StrFmt(
6991 tr("Parent UUID {%RTuuid} of the medium '%s' does not match UUID {%RTuuid} of its parent medium stored in the media registry ('%s')"),
6992 &parentId, location.c_str(),
6993 m->pParent->i_getId().raw(),
6994 pVirtualBox->i_settingsFilePath().c_str());
6995 parentLock.release();
6996 treeLock.release();
6997 throw S_OK;
6998 }
6999 }
7000
7001 /// @todo NEWMEDIA what to do if the parent is not
7002 /// accessible while the diff is? Probably nothing. The
7003 /// real code will detect the mismatch anyway.
7004
7005 treeLock.release();
7006 }
7007 }
7008
7009 mediumSize = VDGetFileSize(hdd, 0);
7010 mediumLogicalSize = VDGetSize(hdd, 0);
7011
7012 success = true;
7013 }
7014 catch (HRESULT aRC)
7015 {
7016 rc = aRC;
7017 }
7018
7019 vrc = VDDestroy(hdd);
7020 if (RT_FAILURE(vrc))
7021 {
7022 lastAccessError = Utf8StrFmt(tr("Could not update and close the medium '%s'%s"),
7023 location.c_str(), i_vdError(vrc).c_str());
7024 success = false;
7025 throw S_OK;
7026 }
7027 }
7028 catch (HRESULT aRC)
7029 {
7030 rc = aRC;
7031 }
7032
7033 autoCaller.release();
7034 treeLock.acquire();
7035 autoCaller.add();
7036 if (FAILED(autoCaller.rc()))
7037 {
7038 m->queryInfoRunning = false;
7039 return autoCaller.rc();
7040 }
7041 alock.acquire();
7042
7043 if (success)
7044 {
7045 m->size = mediumSize;
7046 m->logicalSize = mediumLogicalSize;
7047 m->strLastAccessError.setNull();
7048 }
7049 else
7050 {
7051 m->strLastAccessError = lastAccessError;
7052 Log1WarningFunc(("'%s' is not accessible (error='%s', rc=%Rhrc, vrc=%Rrc)\n",
7053 location.c_str(), m->strLastAccessError.c_str(), rc, vrc));
7054 }
7055
7056 /* Set the proper state according to the result of the check */
7057 if (success)
7058 m->preLockState = MediumState_Created;
7059 else
7060 m->preLockState = MediumState_Inaccessible;
7061
7062 /* unblock anyone waiting for the i_queryInfo results */
7063 qlock.release();
7064 m->queryInfoRunning = false;
7065
7066 pToken->Abandon();
7067 pToken.setNull();
7068
7069 if (FAILED(rc)) return rc;
7070
7071 /* If this is a base image which incorrectly has a parent UUID set,
7072 * repair the image now by zeroing the parent UUID. This is only done
7073 * when we have structural information from a config file, on import
7074 * this is not possible. If someone would accidentally call openMedium
7075 * with a diff image before the base is registered this would destroy
7076 * the diff. Not acceptable. */
7077 if (fRepairImageZeroParentUuid)
7078 {
7079 rc = LockWrite(pToken.asOutParam());
7080 if (FAILED(rc)) return rc;
7081
7082 alock.release();
7083
7084 try
7085 {
7086 PVDISK hdd;
7087 vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
7088 ComAssertRCThrow(vrc, E_FAIL);
7089
7090 try
7091 {
7092 vrc = VDOpen(hdd,
7093 format.c_str(),
7094 location.c_str(),
7095 (uOpenFlags & ~VD_OPEN_FLAGS_READONLY) | m->uOpenFlagsDef,
7096 m->vdImageIfaces);
7097 if (RT_FAILURE(vrc))
7098 throw S_OK;
7099
7100 RTUUID zeroParentUuid;
7101 RTUuidClear(&zeroParentUuid);
7102 vrc = VDSetParentUuid(hdd, 0, &zeroParentUuid);
7103 ComAssertRCThrow(vrc, E_FAIL);
7104 }
7105 catch (HRESULT aRC)
7106 {
7107 rc = aRC;
7108 }
7109
7110 VDDestroy(hdd);
7111 }
7112 catch (HRESULT aRC)
7113 {
7114 rc = aRC;
7115 }
7116
7117 pToken->Abandon();
7118 pToken.setNull();
7119 if (FAILED(rc)) return rc;
7120 }
7121
7122 return rc;
7123}
7124
7125/**
7126 * Performs extra checks if the medium can be closed and returns S_OK in
7127 * this case. Otherwise, returns a respective error message. Called by
7128 * Close() under the medium tree lock and the medium lock.
7129 *
7130 * @note Also reused by Medium::Reset().
7131 *
7132 * @note Caller must hold the media tree write lock!
7133 */
7134HRESULT Medium::i_canClose()
7135{
7136 Assert(m->pVirtualBox->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
7137
7138 if (i_getChildren().size() != 0)
7139 return setError(VBOX_E_OBJECT_IN_USE,
7140 tr("Cannot close medium '%s' because it has %d child media"),
7141 m->strLocationFull.c_str(), i_getChildren().size());
7142
7143 return S_OK;
7144}
7145
7146/**
7147 * Unregisters this medium with mVirtualBox. Called by close() under the medium tree lock.
7148 *
7149 * @note Caller must have locked the media tree lock for writing!
7150 */
7151HRESULT Medium::i_unregisterWithVirtualBox()
7152{
7153 /* Note that we need to de-associate ourselves from the parent to let
7154 * VirtualBox::i_unregisterMedium() properly save the registry */
7155
7156 /* we modify m->pParent and access children */
7157 Assert(m->pVirtualBox->i_getMediaTreeLockHandle().isWriteLockOnCurrentThread());
7158
7159 Medium *pParentBackup = m->pParent;
7160 AssertReturn(i_getChildren().size() == 0, E_FAIL);
7161 if (m->pParent)
7162 i_deparent();
7163
7164 HRESULT rc = m->pVirtualBox->i_unregisterMedium(this);
7165 if (FAILED(rc))
7166 {
7167 if (pParentBackup)
7168 {
7169 // re-associate with the parent as we are still relatives in the registry
7170 i_setParent(pParentBackup);
7171 }
7172 }
7173
7174 return rc;
7175}
7176
7177/**
7178 * Like SetProperty but do not trigger a settings store. Only for internal use!
7179 */
7180HRESULT Medium::i_setPropertyDirect(const Utf8Str &aName, const Utf8Str &aValue)
7181{
7182 AutoCaller autoCaller(this);
7183 if (FAILED(autoCaller.rc())) return autoCaller.rc();
7184
7185 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
7186
7187 switch (m->state)
7188 {
7189 case MediumState_Created:
7190 case MediumState_Inaccessible:
7191 break;
7192 default:
7193 return i_setStateError();
7194 }
7195
7196 m->mapProperties[aName] = aValue;
7197
7198 return S_OK;
7199}
7200
7201/**
7202 * Sets the extended error info according to the current media state.
7203 *
7204 * @note Must be called from under this object's write or read lock.
7205 */
7206HRESULT Medium::i_setStateError()
7207{
7208 HRESULT rc = E_FAIL;
7209
7210 switch (m->state)
7211 {
7212 case MediumState_NotCreated:
7213 {
7214 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
7215 tr("Storage for the medium '%s' is not created"),
7216 m->strLocationFull.c_str());
7217 break;
7218 }
7219 case MediumState_Created:
7220 {
7221 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
7222 tr("Storage for the medium '%s' is already created"),
7223 m->strLocationFull.c_str());
7224 break;
7225 }
7226 case MediumState_LockedRead:
7227 {
7228 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
7229 tr("Medium '%s' is locked for reading by another task"),
7230 m->strLocationFull.c_str());
7231 break;
7232 }
7233 case MediumState_LockedWrite:
7234 {
7235 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
7236 tr("Medium '%s' is locked for writing by another task"),
7237 m->strLocationFull.c_str());
7238 break;
7239 }
7240 case MediumState_Inaccessible:
7241 {
7242 /* be in sync with Console::powerUpThread() */
7243 if (!m->strLastAccessError.isEmpty())
7244 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
7245 tr("Medium '%s' is not accessible. %s"),
7246 m->strLocationFull.c_str(), m->strLastAccessError.c_str());
7247 else
7248 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
7249 tr("Medium '%s' is not accessible"),
7250 m->strLocationFull.c_str());
7251 break;
7252 }
7253 case MediumState_Creating:
7254 {
7255 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
7256 tr("Storage for the medium '%s' is being created"),
7257 m->strLocationFull.c_str());
7258 break;
7259 }
7260 case MediumState_Deleting:
7261 {
7262 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
7263 tr("Storage for the medium '%s' is being deleted"),
7264 m->strLocationFull.c_str());
7265 break;
7266 }
7267 default:
7268 {
7269 AssertFailed();
7270 break;
7271 }
7272 }
7273
7274 return rc;
7275}
7276
7277/**
7278 * Sets the value of m->strLocationFull. The given location must be a fully
7279 * qualified path; relative paths are not supported here.
7280 *
7281 * As a special exception, if the specified location is a file path that ends with '/'
7282 * then the file name part will be generated by this method automatically in the format
7283 * '{\<uuid\>}.\<ext\>' where \<uuid\> is a fresh UUID that this method will generate
7284 * and assign to this medium, and \<ext\> is the default extension for this
7285 * medium's storage format. Note that this procedure requires the media state to
7286 * be NotCreated and will return a failure otherwise.
7287 *
7288 * @param aLocation Location of the storage unit. If the location is a FS-path,
7289 * then it can be relative to the VirtualBox home directory.
7290 * @param aFormat Optional fallback format if it is an import and the format
7291 * cannot be determined.
7292 *
7293 * @note Must be called from under this object's write lock.
7294 */
7295HRESULT Medium::i_setLocation(const Utf8Str &aLocation,
7296 const Utf8Str &aFormat /* = Utf8Str::Empty */)
7297{
7298 AssertReturn(!aLocation.isEmpty(), E_FAIL);
7299
7300 AutoCaller autoCaller(this);
7301 AssertComRCReturnRC(autoCaller.rc());
7302
7303 /* formatObj may be null only when initializing from an existing path and
7304 * no format is known yet */
7305 AssertReturn( (!m->strFormat.isEmpty() && !m->formatObj.isNull())
7306 || ( getObjectState().getState() == ObjectState::InInit
7307 && m->state != MediumState_NotCreated
7308 && m->id.isZero()
7309 && m->strFormat.isEmpty()
7310 && m->formatObj.isNull()),
7311 E_FAIL);
7312
7313 /* are we dealing with a new medium constructed using the existing
7314 * location? */
7315 bool isImport = m->strFormat.isEmpty();
7316
7317 if ( isImport
7318 || ( (m->formatObj->i_getCapabilities() & MediumFormatCapabilities_File)
7319 && !m->hostDrive))
7320 {
7321 Guid id;
7322
7323 Utf8Str locationFull(aLocation);
7324
7325 if (m->state == MediumState_NotCreated)
7326 {
7327 /* must be a file (formatObj must be already known) */
7328 Assert(m->formatObj->i_getCapabilities() & MediumFormatCapabilities_File);
7329
7330 if (RTPathFilename(aLocation.c_str()) == NULL)
7331 {
7332 /* no file name is given (either an empty string or ends with a
7333 * slash), generate a new UUID + file name if the state allows
7334 * this */
7335
7336 ComAssertMsgRet(!m->formatObj->i_getFileExtensions().empty(),
7337 ("Must be at least one extension if it is MediumFormatCapabilities_File\n"),
7338 E_FAIL);
7339
7340 Utf8Str strExt = m->formatObj->i_getFileExtensions().front();
7341 ComAssertMsgRet(!strExt.isEmpty(),
7342 ("Default extension must not be empty\n"),
7343 E_FAIL);
7344
7345 id.create();
7346
7347 locationFull = Utf8StrFmt("%s{%RTuuid}.%s",
7348 aLocation.c_str(), id.raw(), strExt.c_str());
7349 }
7350 }
7351
7352 // we must always have full paths now (if it refers to a file)
7353 if ( ( m->formatObj.isNull()
7354 || m->formatObj->i_getCapabilities() & MediumFormatCapabilities_File)
7355 && !RTPathStartsWithRoot(locationFull.c_str()))
7356 return setError(VBOX_E_FILE_ERROR,
7357 tr("The given path '%s' is not fully qualified"),
7358 locationFull.c_str());
7359
7360 /* detect the backend from the storage unit if importing */
7361 if (isImport)
7362 {
7363 VDTYPE enmType = VDTYPE_INVALID;
7364 char *backendName = NULL;
7365
7366 int vrc = VINF_SUCCESS;
7367
7368 /* is it a file? */
7369 {
7370 RTFILE file;
7371 vrc = RTFileOpen(&file, locationFull.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
7372 if (RT_SUCCESS(vrc))
7373 RTFileClose(file);
7374 }
7375 if (RT_SUCCESS(vrc))
7376 {
7377 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
7378 locationFull.c_str(), &backendName, &enmType);
7379 }
7380 else if ( vrc != VERR_FILE_NOT_FOUND
7381 && vrc != VERR_PATH_NOT_FOUND
7382 && vrc != VERR_ACCESS_DENIED
7383 && locationFull != aLocation)
7384 {
7385 /* assume it's not a file, restore the original location */
7386 locationFull = aLocation;
7387 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
7388 locationFull.c_str(), &backendName, &enmType);
7389 }
7390
7391 if (RT_FAILURE(vrc))
7392 {
7393 if (vrc == VERR_ACCESS_DENIED)
7394 return setError(VBOX_E_FILE_ERROR,
7395 tr("Permission problem accessing the file for the medium '%s' (%Rrc)"),
7396 locationFull.c_str(), vrc);
7397 else if (vrc == VERR_FILE_NOT_FOUND || vrc == VERR_PATH_NOT_FOUND)
7398 return setError(VBOX_E_FILE_ERROR,
7399 tr("Could not find file for the medium '%s' (%Rrc)"),
7400 locationFull.c_str(), vrc);
7401 else if (aFormat.isEmpty())
7402 return setError(VBOX_E_IPRT_ERROR,
7403 tr("Could not get the storage format of the medium '%s' (%Rrc)"),
7404 locationFull.c_str(), vrc);
7405 else
7406 {
7407 HRESULT rc = i_setFormat(aFormat);
7408 /* setFormat() must not fail since we've just used the backend so
7409 * the format object must be there */
7410 AssertComRCReturnRC(rc);
7411 }
7412 }
7413 else if ( enmType == VDTYPE_INVALID
7414 || m->devType != i_convertToDeviceType(enmType))
7415 {
7416 /*
7417 * The user tried to use a image as a device which is not supported
7418 * by the backend.
7419 */
7420 return setError(E_FAIL,
7421 tr("The medium '%s' can't be used as the requested device type"),
7422 locationFull.c_str());
7423 }
7424 else
7425 {
7426 ComAssertRet(backendName != NULL && *backendName != '\0', E_FAIL);
7427
7428 HRESULT rc = i_setFormat(backendName);
7429 RTStrFree(backendName);
7430
7431 /* setFormat() must not fail since we've just used the backend so
7432 * the format object must be there */
7433 AssertComRCReturnRC(rc);
7434 }
7435 }
7436
7437 m->strLocationFull = locationFull;
7438
7439 /* is it still a file? */
7440 if ( (m->formatObj->i_getCapabilities() & MediumFormatCapabilities_File)
7441 && (m->state == MediumState_NotCreated)
7442 )
7443 /* assign a new UUID (this UUID will be used when calling
7444 * VDCreateBase/VDCreateDiff as a wanted UUID). Note that we
7445 * also do that if we didn't generate it to make sure it is
7446 * either generated by us or reset to null */
7447 unconst(m->id) = id;
7448 }
7449 else
7450 m->strLocationFull = aLocation;
7451
7452 return S_OK;
7453}
7454
7455/**
7456 * Checks that the format ID is valid and sets it on success.
7457 *
7458 * Note that this method will caller-reference the format object on success!
7459 * This reference must be released somewhere to let the MediumFormat object be
7460 * uninitialized.
7461 *
7462 * @note Must be called from under this object's write lock.
7463 */
7464HRESULT Medium::i_setFormat(const Utf8Str &aFormat)
7465{
7466 /* get the format object first */
7467 {
7468 SystemProperties *pSysProps = m->pVirtualBox->i_getSystemProperties();
7469 AutoReadLock propsLock(pSysProps COMMA_LOCKVAL_SRC_POS);
7470
7471 unconst(m->formatObj) = pSysProps->i_mediumFormat(aFormat);
7472 if (m->formatObj.isNull())
7473 return setError(E_INVALIDARG,
7474 tr("Invalid medium storage format '%s'"),
7475 aFormat.c_str());
7476
7477 /* get properties (preinsert them as keys in the map). Note that the
7478 * map doesn't grow over the object life time since the set of
7479 * properties is meant to be constant. */
7480
7481 Assert(m->mapProperties.empty());
7482
7483 for (MediumFormat::PropertyArray::const_iterator it = m->formatObj->i_getProperties().begin();
7484 it != m->formatObj->i_getProperties().end();
7485 ++it)
7486 {
7487 m->mapProperties.insert(std::make_pair(it->strName, Utf8Str::Empty));
7488 }
7489 }
7490
7491 unconst(m->strFormat) = aFormat;
7492
7493 return S_OK;
7494}
7495
7496/**
7497 * Converts the Medium device type to the VD type.
7498 */
7499VDTYPE Medium::i_convertDeviceType()
7500{
7501 VDTYPE enmType;
7502
7503 switch (m->devType)
7504 {
7505 case DeviceType_HardDisk:
7506 enmType = VDTYPE_HDD;
7507 break;
7508 case DeviceType_DVD:
7509 enmType = VDTYPE_OPTICAL_DISC;
7510 break;
7511 case DeviceType_Floppy:
7512 enmType = VDTYPE_FLOPPY;
7513 break;
7514 default:
7515 ComAssertFailedRet(VDTYPE_INVALID);
7516 }
7517
7518 return enmType;
7519}
7520
7521/**
7522 * Converts from the VD type to the medium type.
7523 */
7524DeviceType_T Medium::i_convertToDeviceType(VDTYPE enmType)
7525{
7526 DeviceType_T devType;
7527
7528 switch (enmType)
7529 {
7530 case VDTYPE_HDD:
7531 devType = DeviceType_HardDisk;
7532 break;
7533 case VDTYPE_OPTICAL_DISC:
7534 devType = DeviceType_DVD;
7535 break;
7536 case VDTYPE_FLOPPY:
7537 devType = DeviceType_Floppy;
7538 break;
7539 default:
7540 ComAssertFailedRet(DeviceType_Null);
7541 }
7542
7543 return devType;
7544}
7545
7546/**
7547 * Internal method which checks whether a property name is for a filter plugin.
7548 */
7549bool Medium::i_isPropertyForFilter(const com::Utf8Str &aName)
7550{
7551 /* If the name contains "/" use the part before as a filter name and lookup the filter. */
7552 size_t offSlash;
7553 if ((offSlash = aName.find("/", 0)) != aName.npos)
7554 {
7555 com::Utf8Str strFilter;
7556 com::Utf8Str strKey;
7557
7558 HRESULT rc = strFilter.assignEx(aName, 0, offSlash);
7559 if (FAILED(rc))
7560 return false;
7561
7562 rc = strKey.assignEx(aName, offSlash + 1, aName.length() - offSlash - 1); /* Skip slash */
7563 if (FAILED(rc))
7564 return false;
7565
7566 VDFILTERINFO FilterInfo;
7567 int vrc = VDFilterInfoOne(strFilter.c_str(), &FilterInfo);
7568 if (RT_SUCCESS(vrc))
7569 {
7570 /* Check that the property exists. */
7571 PCVDCONFIGINFO paConfig = FilterInfo.paConfigInfo;
7572 while (paConfig->pszKey)
7573 {
7574 if (strKey.equals(paConfig->pszKey))
7575 return true;
7576 paConfig++;
7577 }
7578 }
7579 }
7580
7581 return false;
7582}
7583
7584/**
7585 * Returns the last error message collected by the i_vdErrorCall callback and
7586 * resets it.
7587 *
7588 * The error message is returned prepended with a dot and a space, like this:
7589 * <code>
7590 * ". <error_text> (%Rrc)"
7591 * </code>
7592 * to make it easily appendable to a more general error message. The @c %Rrc
7593 * format string is given @a aVRC as an argument.
7594 *
7595 * If there is no last error message collected by i_vdErrorCall or if it is a
7596 * null or empty string, then this function returns the following text:
7597 * <code>
7598 * " (%Rrc)"
7599 * </code>
7600 *
7601 * @note Doesn't do any object locking; it is assumed that the caller makes sure
7602 * the callback isn't called by more than one thread at a time.
7603 *
7604 * @param aVRC VBox error code to use when no error message is provided.
7605 */
7606Utf8Str Medium::i_vdError(int aVRC)
7607{
7608 Utf8Str error;
7609
7610 if (m->vdError.isEmpty())
7611 error = Utf8StrFmt(" (%Rrc)", aVRC);
7612 else
7613 error = Utf8StrFmt(".\n%s", m->vdError.c_str());
7614
7615 m->vdError.setNull();
7616
7617 return error;
7618}
7619
7620/**
7621 * Error message callback.
7622 *
7623 * Puts the reported error message to the m->vdError field.
7624 *
7625 * @note Doesn't do any object locking; it is assumed that the caller makes sure
7626 * the callback isn't called by more than one thread at a time.
7627 *
7628 * @param pvUser The opaque data passed on container creation.
7629 * @param rc The VBox error code.
7630 * @param SRC_POS Use RT_SRC_POS.
7631 * @param pszFormat Error message format string.
7632 * @param va Error message arguments.
7633 */
7634/*static*/
7635DECLCALLBACK(void) Medium::i_vdErrorCall(void *pvUser, int rc, RT_SRC_POS_DECL,
7636 const char *pszFormat, va_list va)
7637{
7638 NOREF(pszFile); NOREF(iLine); NOREF(pszFunction); /* RT_SRC_POS_DECL */
7639
7640 Medium *that = static_cast<Medium*>(pvUser);
7641 AssertReturnVoid(that != NULL);
7642
7643 if (that->m->vdError.isEmpty())
7644 that->m->vdError =
7645 Utf8StrFmt("%s (%Rrc)", Utf8Str(pszFormat, va).c_str(), rc);
7646 else
7647 that->m->vdError =
7648 Utf8StrFmt("%s.\n%s (%Rrc)", that->m->vdError.c_str(),
7649 Utf8Str(pszFormat, va).c_str(), rc);
7650}
7651
7652/* static */
7653DECLCALLBACK(bool) Medium::i_vdConfigAreKeysValid(void *pvUser,
7654 const char * /* pszzValid */)
7655{
7656 Medium *that = static_cast<Medium*>(pvUser);
7657 AssertReturn(that != NULL, false);
7658
7659 /* we always return true since the only keys we have are those found in
7660 * VDBACKENDINFO */
7661 return true;
7662}
7663
7664/* static */
7665DECLCALLBACK(int) Medium::i_vdConfigQuerySize(void *pvUser,
7666 const char *pszName,
7667 size_t *pcbValue)
7668{
7669 AssertReturn(VALID_PTR(pcbValue), VERR_INVALID_POINTER);
7670
7671 Medium *that = static_cast<Medium*>(pvUser);
7672 AssertReturn(that != NULL, VERR_GENERAL_FAILURE);
7673
7674 settings::StringsMap::const_iterator it = that->m->mapProperties.find(Utf8Str(pszName));
7675 if (it == that->m->mapProperties.end())
7676 return VERR_CFGM_VALUE_NOT_FOUND;
7677
7678 /* we interpret null values as "no value" in Medium */
7679 if (it->second.isEmpty())
7680 return VERR_CFGM_VALUE_NOT_FOUND;
7681
7682 *pcbValue = it->second.length() + 1 /* include terminator */;
7683
7684 return VINF_SUCCESS;
7685}
7686
7687/* static */
7688DECLCALLBACK(int) Medium::i_vdConfigQuery(void *pvUser,
7689 const char *pszName,
7690 char *pszValue,
7691 size_t cchValue)
7692{
7693 AssertReturn(VALID_PTR(pszValue), VERR_INVALID_POINTER);
7694
7695 Medium *that = static_cast<Medium*>(pvUser);
7696 AssertReturn(that != NULL, VERR_GENERAL_FAILURE);
7697
7698 settings::StringsMap::const_iterator it = that->m->mapProperties.find(Utf8Str(pszName));
7699 if (it == that->m->mapProperties.end())
7700 return VERR_CFGM_VALUE_NOT_FOUND;
7701
7702 /* we interpret null values as "no value" in Medium */
7703 if (it->second.isEmpty())
7704 return VERR_CFGM_VALUE_NOT_FOUND;
7705
7706 const Utf8Str &value = it->second;
7707 if (value.length() >= cchValue)
7708 return VERR_CFGM_NOT_ENOUGH_SPACE;
7709
7710 memcpy(pszValue, value.c_str(), value.length() + 1);
7711
7712 return VINF_SUCCESS;
7713}
7714
7715DECLCALLBACK(int) Medium::i_vdTcpSocketCreate(uint32_t fFlags, PVDSOCKET pSock)
7716{
7717 PVDSOCKETINT pSocketInt = NULL;
7718
7719 if ((fFlags & VD_INTERFACETCPNET_CONNECT_EXTENDED_SELECT) != 0)
7720 return VERR_NOT_SUPPORTED;
7721
7722 pSocketInt = (PVDSOCKETINT)RTMemAllocZ(sizeof(VDSOCKETINT));
7723 if (!pSocketInt)
7724 return VERR_NO_MEMORY;
7725
7726 pSocketInt->hSocket = NIL_RTSOCKET;
7727 *pSock = pSocketInt;
7728 return VINF_SUCCESS;
7729}
7730
7731DECLCALLBACK(int) Medium::i_vdTcpSocketDestroy(VDSOCKET Sock)
7732{
7733 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7734
7735 if (pSocketInt->hSocket != NIL_RTSOCKET)
7736 RTTcpClientCloseEx(pSocketInt->hSocket, false /*fGracefulShutdown*/);
7737
7738 RTMemFree(pSocketInt);
7739
7740 return VINF_SUCCESS;
7741}
7742
7743DECLCALLBACK(int) Medium::i_vdTcpClientConnect(VDSOCKET Sock, const char *pszAddress, uint32_t uPort,
7744 RTMSINTERVAL cMillies)
7745{
7746 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7747
7748 return RTTcpClientConnectEx(pszAddress, uPort, &pSocketInt->hSocket, cMillies, NULL);
7749}
7750
7751DECLCALLBACK(int) Medium::i_vdTcpClientClose(VDSOCKET Sock)
7752{
7753 int rc = VINF_SUCCESS;
7754 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7755
7756 rc = RTTcpClientCloseEx(pSocketInt->hSocket, false /*fGracefulShutdown*/);
7757 pSocketInt->hSocket = NIL_RTSOCKET;
7758 return rc;
7759}
7760
7761DECLCALLBACK(bool) Medium::i_vdTcpIsClientConnected(VDSOCKET Sock)
7762{
7763 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7764 return pSocketInt->hSocket != NIL_RTSOCKET;
7765}
7766
7767DECLCALLBACK(int) Medium::i_vdTcpSelectOne(VDSOCKET Sock, RTMSINTERVAL cMillies)
7768{
7769 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7770 return RTTcpSelectOne(pSocketInt->hSocket, cMillies);
7771}
7772
7773DECLCALLBACK(int) Medium::i_vdTcpRead(VDSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
7774{
7775 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7776 return RTTcpRead(pSocketInt->hSocket, pvBuffer, cbBuffer, pcbRead);
7777}
7778
7779DECLCALLBACK(int) Medium::i_vdTcpWrite(VDSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
7780{
7781 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7782 return RTTcpWrite(pSocketInt->hSocket, pvBuffer, cbBuffer);
7783}
7784
7785DECLCALLBACK(int) Medium::i_vdTcpSgWrite(VDSOCKET Sock, PCRTSGBUF pSgBuf)
7786{
7787 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7788 return RTTcpSgWrite(pSocketInt->hSocket, pSgBuf);
7789}
7790
7791DECLCALLBACK(int) Medium::i_vdTcpFlush(VDSOCKET Sock)
7792{
7793 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7794 return RTTcpFlush(pSocketInt->hSocket);
7795}
7796
7797DECLCALLBACK(int) Medium::i_vdTcpSetSendCoalescing(VDSOCKET Sock, bool fEnable)
7798{
7799 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7800 return RTTcpSetSendCoalescing(pSocketInt->hSocket, fEnable);
7801}
7802
7803DECLCALLBACK(int) Medium::i_vdTcpGetLocalAddress(VDSOCKET Sock, PRTNETADDR pAddr)
7804{
7805 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7806 return RTTcpGetLocalAddress(pSocketInt->hSocket, pAddr);
7807}
7808
7809DECLCALLBACK(int) Medium::i_vdTcpGetPeerAddress(VDSOCKET Sock, PRTNETADDR pAddr)
7810{
7811 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
7812 return RTTcpGetPeerAddress(pSocketInt->hSocket, pAddr);
7813}
7814
7815DECLCALLBACK(bool) Medium::i_vdCryptoConfigAreKeysValid(void *pvUser, const char *pszzValid)
7816{
7817 /* Just return always true here. */
7818 NOREF(pvUser);
7819 NOREF(pszzValid);
7820 return true;
7821}
7822
7823DECLCALLBACK(int) Medium::i_vdCryptoConfigQuerySize(void *pvUser, const char *pszName, size_t *pcbValue)
7824{
7825 Medium::CryptoFilterSettings *pSettings = (Medium::CryptoFilterSettings *)pvUser;
7826 AssertPtrReturn(pSettings, VERR_GENERAL_FAILURE);
7827 AssertReturn(VALID_PTR(pcbValue), VERR_INVALID_POINTER);
7828
7829 size_t cbValue = 0;
7830 if (!strcmp(pszName, "Algorithm"))
7831 cbValue = strlen(pSettings->pszCipher) + 1;
7832 else if (!strcmp(pszName, "KeyId"))
7833 cbValue = sizeof("irrelevant");
7834 else if (!strcmp(pszName, "KeyStore"))
7835 {
7836 if (!pSettings->pszKeyStoreLoad)
7837 return VERR_CFGM_VALUE_NOT_FOUND;
7838 cbValue = strlen(pSettings->pszKeyStoreLoad) + 1;
7839 }
7840 else if (!strcmp(pszName, "CreateKeyStore"))
7841 cbValue = 2; /* Single digit + terminator. */
7842 else
7843 return VERR_CFGM_VALUE_NOT_FOUND;
7844
7845 *pcbValue = cbValue + 1 /* include terminator */;
7846
7847 return VINF_SUCCESS;
7848}
7849
7850DECLCALLBACK(int) Medium::i_vdCryptoConfigQuery(void *pvUser, const char *pszName,
7851 char *pszValue, size_t cchValue)
7852{
7853 Medium::CryptoFilterSettings *pSettings = (Medium::CryptoFilterSettings *)pvUser;
7854 AssertPtrReturn(pSettings, VERR_GENERAL_FAILURE);
7855 AssertReturn(VALID_PTR(pszValue), VERR_INVALID_POINTER);
7856
7857 const char *psz = NULL;
7858 if (!strcmp(pszName, "Algorithm"))
7859 psz = pSettings->pszCipher;
7860 else if (!strcmp(pszName, "KeyId"))
7861 psz = "irrelevant";
7862 else if (!strcmp(pszName, "KeyStore"))
7863 psz = pSettings->pszKeyStoreLoad;
7864 else if (!strcmp(pszName, "CreateKeyStore"))
7865 {
7866 if (pSettings->fCreateKeyStore)
7867 psz = "1";
7868 else
7869 psz = "0";
7870 }
7871 else
7872 return VERR_CFGM_VALUE_NOT_FOUND;
7873
7874 size_t cch = strlen(psz);
7875 if (cch >= cchValue)
7876 return VERR_CFGM_NOT_ENOUGH_SPACE;
7877
7878 memcpy(pszValue, psz, cch + 1);
7879 return VINF_SUCCESS;
7880}
7881
7882DECLCALLBACK(int) Medium::i_vdCryptoKeyRetain(void *pvUser, const char *pszId,
7883 const uint8_t **ppbKey, size_t *pcbKey)
7884{
7885 Medium::CryptoFilterSettings *pSettings = (Medium::CryptoFilterSettings *)pvUser;
7886 NOREF(pszId);
7887 NOREF(ppbKey);
7888 NOREF(pcbKey);
7889 AssertPtrReturn(pSettings, VERR_GENERAL_FAILURE);
7890 AssertMsgFailedReturn(("This method should not be called here!\n"), VERR_INVALID_STATE);
7891}
7892
7893DECLCALLBACK(int) Medium::i_vdCryptoKeyRelease(void *pvUser, const char *pszId)
7894{
7895 Medium::CryptoFilterSettings *pSettings = (Medium::CryptoFilterSettings *)pvUser;
7896 NOREF(pszId);
7897 AssertPtrReturn(pSettings, VERR_GENERAL_FAILURE);
7898 AssertMsgFailedReturn(("This method should not be called here!\n"), VERR_INVALID_STATE);
7899}
7900
7901DECLCALLBACK(int) Medium::i_vdCryptoKeyStorePasswordRetain(void *pvUser, const char *pszId, const char **ppszPassword)
7902{
7903 Medium::CryptoFilterSettings *pSettings = (Medium::CryptoFilterSettings *)pvUser;
7904 AssertPtrReturn(pSettings, VERR_GENERAL_FAILURE);
7905
7906 NOREF(pszId);
7907 *ppszPassword = pSettings->pszPassword;
7908 return VINF_SUCCESS;
7909}
7910
7911DECLCALLBACK(int) Medium::i_vdCryptoKeyStorePasswordRelease(void *pvUser, const char *pszId)
7912{
7913 Medium::CryptoFilterSettings *pSettings = (Medium::CryptoFilterSettings *)pvUser;
7914 AssertPtrReturn(pSettings, VERR_GENERAL_FAILURE);
7915 NOREF(pszId);
7916 return VINF_SUCCESS;
7917}
7918
7919DECLCALLBACK(int) Medium::i_vdCryptoKeyStoreSave(void *pvUser, const void *pvKeyStore, size_t cbKeyStore)
7920{
7921 Medium::CryptoFilterSettings *pSettings = (Medium::CryptoFilterSettings *)pvUser;
7922 AssertPtrReturn(pSettings, VERR_GENERAL_FAILURE);
7923
7924 pSettings->pszKeyStore = (char *)RTMemAllocZ(cbKeyStore);
7925 if (!pSettings->pszKeyStore)
7926 return VERR_NO_MEMORY;
7927
7928 memcpy(pSettings->pszKeyStore, pvKeyStore, cbKeyStore);
7929 return VINF_SUCCESS;
7930}
7931
7932DECLCALLBACK(int) Medium::i_vdCryptoKeyStoreReturnParameters(void *pvUser, const char *pszCipher,
7933 const uint8_t *pbDek, size_t cbDek)
7934{
7935 Medium::CryptoFilterSettings *pSettings = (Medium::CryptoFilterSettings *)pvUser;
7936 AssertPtrReturn(pSettings, VERR_GENERAL_FAILURE);
7937
7938 pSettings->pszCipherReturned = RTStrDup(pszCipher);
7939 pSettings->pbDek = pbDek;
7940 pSettings->cbDek = cbDek;
7941
7942 return pSettings->pszCipherReturned ? VINF_SUCCESS : VERR_NO_MEMORY;
7943}
7944
7945/**
7946 * Creates a read-only VDISK instance for this medium.
7947 *
7948 * @note Caller should not hold any medium related locks as this method will
7949 * acquire the medium lock for writing and others (VirtualBox).
7950 *
7951 * @returns COM status code.
7952 * @param pKeyStore The key store.
7953 * @param ppHdd Where to return the pointer to the VDISK on
7954 * success.
7955 * @param pMediumLockList The lock list to populate and lock. Caller
7956 * is responsible for calling the destructor or
7957 * MediumLockList::Clear() after destroying
7958 * @a *ppHdd
7959 * @param pCryptoSettingsRead The crypto read settings to use for setting
7960 * up decryption of the VDISK. This object
7961 * must be alive until the VDISK is destroyed!
7962 */
7963HRESULT Medium::i_openHddForReading(SecretKeyStore *pKeyStore, PVDISK *ppHdd, MediumLockList *pMediumLockList,
7964 Medium::CryptoFilterSettings *pCryptoSettingsRead)
7965{
7966 /*
7967 * Create the media lock list and lock the media.
7968 */
7969 HRESULT hrc = i_createMediumLockList(true /* fFailIfInaccessible */,
7970 NULL /* pToLockWrite */,
7971 false /* fMediumLockWriteAll */,
7972 NULL,
7973 *pMediumLockList);
7974 if (SUCCEEDED(hrc))
7975 hrc = pMediumLockList->Lock();
7976 if (FAILED(hrc))
7977 return hrc;
7978
7979 /*
7980 * Get the base medium before write locking this medium.
7981 */
7982 ComObjPtr<Medium> pBase = i_getBase();
7983 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7984
7985 /*
7986 * Create the VDISK instance.
7987 */
7988 PVDISK pHdd;
7989 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &pHdd);
7990 AssertRCReturn(vrc, E_FAIL);
7991
7992 /*
7993 * Goto avoidance using try/catch/throw(HRESULT).
7994 */
7995 try
7996 {
7997 settings::StringsMap::iterator itKeyStore = pBase->m->mapProperties.find("CRYPT/KeyStore");
7998 if (itKeyStore != pBase->m->mapProperties.end())
7999 {
8000 settings::StringsMap::iterator itKeyId = pBase->m->mapProperties.find("CRYPT/KeyId");
8001
8002#ifdef VBOX_WITH_EXTPACK
8003 ExtPackManager *pExtPackManager = m->pVirtualBox->i_getExtPackManager();
8004 if (pExtPackManager->i_isExtPackUsable(ORACLE_PUEL_EXTPACK_NAME))
8005 {
8006 /* Load the plugin */
8007 Utf8Str strPlugin;
8008 hrc = pExtPackManager->i_getLibraryPathForExtPack(g_szVDPlugin, ORACLE_PUEL_EXTPACK_NAME, &strPlugin);
8009 if (SUCCEEDED(hrc))
8010 {
8011 vrc = VDPluginLoadFromFilename(strPlugin.c_str());
8012 if (RT_FAILURE(vrc))
8013 throw setError(VBOX_E_NOT_SUPPORTED,
8014 tr("Retrieving encryption settings of the image failed because the encryption plugin could not be loaded (%s)"),
8015 i_vdError(vrc).c_str());
8016 }
8017 else
8018 throw setError(VBOX_E_NOT_SUPPORTED,
8019 tr("Encryption is not supported because the extension pack '%s' is missing the encryption plugin (old extension pack installed?)"),
8020 ORACLE_PUEL_EXTPACK_NAME);
8021 }
8022 else
8023 throw setError(VBOX_E_NOT_SUPPORTED,
8024 tr("Encryption is not supported because the extension pack '%s' is missing"),
8025 ORACLE_PUEL_EXTPACK_NAME);
8026#else
8027 throw setError(VBOX_E_NOT_SUPPORTED,
8028 tr("Encryption is not supported because extension pack support is not built in"));
8029#endif
8030
8031 if (itKeyId == pBase->m->mapProperties.end())
8032 throw setError(VBOX_E_INVALID_OBJECT_STATE,
8033 tr("Image '%s' is configured for encryption but doesn't has a key identifier set"),
8034 pBase->m->strLocationFull.c_str());
8035
8036 /* Find the proper secret key in the key store. */
8037 if (!pKeyStore)
8038 throw setError(VBOX_E_INVALID_OBJECT_STATE,
8039 tr("Image '%s' is configured for encryption but there is no key store to retrieve the password from"),
8040 pBase->m->strLocationFull.c_str());
8041
8042 SecretKey *pKey = NULL;
8043 vrc = pKeyStore->retainSecretKey(itKeyId->second, &pKey);
8044 if (RT_FAILURE(vrc))
8045 throw setError(VBOX_E_INVALID_OBJECT_STATE,
8046 tr("Failed to retrieve the secret key with ID \"%s\" from the store (%Rrc)"),
8047 itKeyId->second.c_str(), vrc);
8048
8049 i_taskEncryptSettingsSetup(pCryptoSettingsRead, NULL, itKeyStore->second.c_str(), (const char *)pKey->getKeyBuffer(),
8050 false /* fCreateKeyStore */);
8051 vrc = VDFilterAdd(pHdd, "CRYPT", VD_FILTER_FLAGS_READ, pCryptoSettingsRead->vdFilterIfaces);
8052 pKeyStore->releaseSecretKey(itKeyId->second);
8053 if (vrc == VERR_VD_PASSWORD_INCORRECT)
8054 throw setError(VBOX_E_PASSWORD_INCORRECT, tr("The password to decrypt the image is incorrect"));
8055 if (RT_FAILURE(vrc))
8056 throw setError(VBOX_E_INVALID_OBJECT_STATE, tr("Failed to load the decryption filter: %s"),
8057 i_vdError(vrc).c_str());
8058 }
8059
8060 /*
8061 * Open all media in the source chain.
8062 */
8063 MediumLockList::Base::const_iterator sourceListBegin = pMediumLockList->GetBegin();
8064 MediumLockList::Base::const_iterator sourceListEnd = pMediumLockList->GetEnd();
8065 for (MediumLockList::Base::const_iterator it = sourceListBegin; it != sourceListEnd; ++it)
8066 {
8067 const MediumLock &mediumLock = *it;
8068 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
8069 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
8070
8071 /* sanity check */
8072 Assert(pMedium->m->state == MediumState_LockedRead);
8073
8074 /* Open all media in read-only mode. */
8075 vrc = VDOpen(pHdd,
8076 pMedium->m->strFormat.c_str(),
8077 pMedium->m->strLocationFull.c_str(),
8078 VD_OPEN_FLAGS_READONLY | m->uOpenFlagsDef,
8079 pMedium->m->vdImageIfaces);
8080 if (RT_FAILURE(vrc))
8081 throw setError(VBOX_E_FILE_ERROR,
8082 tr("Could not open the medium storage unit '%s'%s"),
8083 pMedium->m->strLocationFull.c_str(),
8084 i_vdError(vrc).c_str());
8085 }
8086
8087 Assert(m->state == MediumState_LockedRead);
8088
8089 /*
8090 * Done!
8091 */
8092 *ppHdd = pHdd;
8093 return S_OK;
8094 }
8095 catch (HRESULT hrc2)
8096 {
8097 hrc = hrc2;
8098 }
8099
8100 VDDestroy(pHdd);
8101 return hrc;
8102
8103}
8104
8105/**
8106 * Implementation code for the "create base" task.
8107 *
8108 * This only gets started from Medium::CreateBaseStorage() and always runs
8109 * asynchronously. As a result, we always save the VirtualBox.xml file when
8110 * we're done here.
8111 *
8112 * @param task
8113 * @return
8114 */
8115HRESULT Medium::i_taskCreateBaseHandler(Medium::CreateBaseTask &task)
8116{
8117 /** @todo r=klaus The code below needs to be double checked with regard
8118 * to lock order violations, it probably causes lock order issues related
8119 * to the AutoCaller usage. */
8120 HRESULT rc = S_OK;
8121
8122 /* these parameters we need after creation */
8123 uint64_t size = 0, logicalSize = 0;
8124 MediumVariant_T variant = MediumVariant_Standard;
8125 bool fGenerateUuid = false;
8126
8127 try
8128 {
8129 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
8130
8131 /* The object may request a specific UUID (through a special form of
8132 * the setLocation() argument). Otherwise we have to generate it */
8133 Guid id = m->id;
8134
8135 fGenerateUuid = id.isZero();
8136 if (fGenerateUuid)
8137 {
8138 id.create();
8139 /* VirtualBox::i_registerMedium() will need UUID */
8140 unconst(m->id) = id;
8141 }
8142
8143 Utf8Str format(m->strFormat);
8144 Utf8Str location(m->strLocationFull);
8145 uint64_t capabilities = m->formatObj->i_getCapabilities();
8146 ComAssertThrow(capabilities & ( MediumFormatCapabilities_CreateFixed
8147 | MediumFormatCapabilities_CreateDynamic), E_FAIL);
8148 Assert(m->state == MediumState_Creating);
8149
8150 PVDISK hdd;
8151 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
8152 ComAssertRCThrow(vrc, E_FAIL);
8153
8154 /* unlock before the potentially lengthy operation */
8155 thisLock.release();
8156
8157 try
8158 {
8159 /* ensure the directory exists */
8160 if (capabilities & MediumFormatCapabilities_File)
8161 {
8162 rc = VirtualBox::i_ensureFilePathExists(location, !(task.mVariant & MediumVariant_NoCreateDir) /* fCreate */);
8163 if (FAILED(rc))
8164 throw rc;
8165 }
8166
8167 VDGEOMETRY geo = { 0, 0, 0 }; /* auto-detect */
8168
8169 vrc = VDCreateBase(hdd,
8170 format.c_str(),
8171 location.c_str(),
8172 task.mSize,
8173 task.mVariant & ~MediumVariant_NoCreateDir,
8174 NULL,
8175 &geo,
8176 &geo,
8177 id.raw(),
8178 VD_OPEN_FLAGS_NORMAL | m->uOpenFlagsDef,
8179 m->vdImageIfaces,
8180 task.mVDOperationIfaces);
8181 if (RT_FAILURE(vrc))
8182 {
8183 if (vrc == VERR_VD_INVALID_TYPE)
8184 throw setError(VBOX_E_FILE_ERROR,
8185 tr("Parameters for creating the medium storage unit '%s' are invalid%s"),
8186 location.c_str(), i_vdError(vrc).c_str());
8187 else
8188 throw setError(VBOX_E_FILE_ERROR,
8189 tr("Could not create the medium storage unit '%s'%s"),
8190 location.c_str(), i_vdError(vrc).c_str());
8191 }
8192
8193 size = VDGetFileSize(hdd, 0);
8194 logicalSize = VDGetSize(hdd, 0);
8195 unsigned uImageFlags;
8196 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
8197 if (RT_SUCCESS(vrc))
8198 variant = (MediumVariant_T)uImageFlags;
8199 }
8200 catch (HRESULT aRC) { rc = aRC; }
8201
8202 VDDestroy(hdd);
8203 }
8204 catch (HRESULT aRC) { rc = aRC; }
8205
8206 if (SUCCEEDED(rc))
8207 {
8208 /* register with mVirtualBox as the last step and move to
8209 * Created state only on success (leaving an orphan file is
8210 * better than breaking media registry consistency) */
8211 AutoWriteLock treeLock(m->pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
8212 ComObjPtr<Medium> pMedium;
8213 rc = m->pVirtualBox->i_registerMedium(this, &pMedium, treeLock);
8214 Assert(pMedium == NULL || this == pMedium);
8215 }
8216
8217 // re-acquire the lock before changing state
8218 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
8219
8220 if (SUCCEEDED(rc))
8221 {
8222 m->state = MediumState_Created;
8223
8224 m->size = size;
8225 m->logicalSize = logicalSize;
8226 m->variant = variant;
8227
8228 thisLock.release();
8229 i_markRegistriesModified();
8230 if (task.isAsync())
8231 {
8232 // in asynchronous mode, save settings now
8233 m->pVirtualBox->i_saveModifiedRegistries();
8234 }
8235 }
8236 else
8237 {
8238 /* back to NotCreated on failure */
8239 m->state = MediumState_NotCreated;
8240
8241 /* reset UUID to prevent it from being reused next time */
8242 if (fGenerateUuid)
8243 unconst(m->id).clear();
8244 }
8245
8246 return rc;
8247}
8248
8249/**
8250 * Implementation code for the "create diff" task.
8251 *
8252 * This task always gets started from Medium::createDiffStorage() and can run
8253 * synchronously or asynchronously depending on the "wait" parameter passed to
8254 * that function. If we run synchronously, the caller expects the medium
8255 * registry modification to be set before returning; otherwise (in asynchronous
8256 * mode), we save the settings ourselves.
8257 *
8258 * @param task
8259 * @return
8260 */
8261HRESULT Medium::i_taskCreateDiffHandler(Medium::CreateDiffTask &task)
8262{
8263 /** @todo r=klaus The code below needs to be double checked with regard
8264 * to lock order violations, it probably causes lock order issues related
8265 * to the AutoCaller usage. */
8266 HRESULT rcTmp = S_OK;
8267
8268 const ComObjPtr<Medium> &pTarget = task.mTarget;
8269
8270 uint64_t size = 0, logicalSize = 0;
8271 MediumVariant_T variant = MediumVariant_Standard;
8272 bool fGenerateUuid = false;
8273
8274 try
8275 {
8276 if (i_getDepth() >= SETTINGS_MEDIUM_DEPTH_MAX)
8277 {
8278 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
8279 throw setError(VBOX_E_INVALID_OBJECT_STATE,
8280 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"),
8281 m->strLocationFull.c_str());
8282 }
8283
8284 /* Lock both in {parent,child} order. */
8285 AutoMultiWriteLock2 mediaLock(this, pTarget COMMA_LOCKVAL_SRC_POS);
8286
8287 /* The object may request a specific UUID (through a special form of
8288 * the setLocation() argument). Otherwise we have to generate it */
8289 Guid targetId = pTarget->m->id;
8290
8291 fGenerateUuid = targetId.isZero();
8292 if (fGenerateUuid)
8293 {
8294 targetId.create();
8295 /* VirtualBox::i_registerMedium() will need UUID */
8296 unconst(pTarget->m->id) = targetId;
8297 }
8298
8299 Guid id = m->id;
8300
8301 Utf8Str targetFormat(pTarget->m->strFormat);
8302 Utf8Str targetLocation(pTarget->m->strLocationFull);
8303 uint64_t capabilities = pTarget->m->formatObj->i_getCapabilities();
8304 ComAssertThrow(capabilities & MediumFormatCapabilities_CreateDynamic, E_FAIL);
8305
8306 Assert(pTarget->m->state == MediumState_Creating);
8307 Assert(m->state == MediumState_LockedRead);
8308
8309 PVDISK hdd;
8310 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
8311 ComAssertRCThrow(vrc, E_FAIL);
8312
8313 /* the two media are now protected by their non-default states;
8314 * unlock the media before the potentially lengthy operation */
8315 mediaLock.release();
8316
8317 try
8318 {
8319 /* Open all media in the target chain but the last. */
8320 MediumLockList::Base::const_iterator targetListBegin =
8321 task.mpMediumLockList->GetBegin();
8322 MediumLockList::Base::const_iterator targetListEnd =
8323 task.mpMediumLockList->GetEnd();
8324 for (MediumLockList::Base::const_iterator it = targetListBegin;
8325 it != targetListEnd;
8326 ++it)
8327 {
8328 const MediumLock &mediumLock = *it;
8329 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
8330
8331 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
8332
8333 /* Skip over the target diff medium */
8334 if (pMedium->m->state == MediumState_Creating)
8335 continue;
8336
8337 /* sanity check */
8338 Assert(pMedium->m->state == MediumState_LockedRead);
8339
8340 /* Open all media in appropriate mode. */
8341 vrc = VDOpen(hdd,
8342 pMedium->m->strFormat.c_str(),
8343 pMedium->m->strLocationFull.c_str(),
8344 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO | m->uOpenFlagsDef,
8345 pMedium->m->vdImageIfaces);
8346 if (RT_FAILURE(vrc))
8347 throw setError(VBOX_E_FILE_ERROR,
8348 tr("Could not open the medium storage unit '%s'%s"),
8349 pMedium->m->strLocationFull.c_str(),
8350 i_vdError(vrc).c_str());
8351 }
8352
8353 /* ensure the target directory exists */
8354 if (capabilities & MediumFormatCapabilities_File)
8355 {
8356 HRESULT rc = VirtualBox::i_ensureFilePathExists(targetLocation,
8357 !(task.mVariant & MediumVariant_NoCreateDir) /* fCreate */);
8358 if (FAILED(rc))
8359 throw rc;
8360 }
8361
8362 vrc = VDCreateDiff(hdd,
8363 targetFormat.c_str(),
8364 targetLocation.c_str(),
8365 (task.mVariant & ~MediumVariant_NoCreateDir) | VD_IMAGE_FLAGS_DIFF,
8366 NULL,
8367 targetId.raw(),
8368 id.raw(),
8369 VD_OPEN_FLAGS_NORMAL | m->uOpenFlagsDef,
8370 pTarget->m->vdImageIfaces,
8371 task.mVDOperationIfaces);
8372 if (RT_FAILURE(vrc))
8373 {
8374 if (vrc == VERR_VD_INVALID_TYPE)
8375 throw setError(VBOX_E_FILE_ERROR,
8376 tr("Parameters for creating the differencing medium storage unit '%s' are invalid%s"),
8377 targetLocation.c_str(), i_vdError(vrc).c_str());
8378 else
8379 throw setError(VBOX_E_FILE_ERROR,
8380 tr("Could not create the differencing medium storage unit '%s'%s"),
8381 targetLocation.c_str(), i_vdError(vrc).c_str());
8382 }
8383
8384 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
8385 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE);
8386 unsigned uImageFlags;
8387 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
8388 if (RT_SUCCESS(vrc))
8389 variant = (MediumVariant_T)uImageFlags;
8390 }
8391 catch (HRESULT aRC) { rcTmp = aRC; }
8392
8393 VDDestroy(hdd);
8394 }
8395 catch (HRESULT aRC) { rcTmp = aRC; }
8396
8397 MultiResult mrc(rcTmp);
8398
8399 if (SUCCEEDED(mrc))
8400 {
8401 AutoWriteLock treeLock(m->pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
8402
8403 Assert(pTarget->m->pParent.isNull());
8404
8405 /* associate child with the parent, maximum depth was checked above */
8406 pTarget->i_setParent(this);
8407
8408 /* diffs for immutable media are auto-reset by default */
8409 bool fAutoReset;
8410 {
8411 ComObjPtr<Medium> pBase = i_getBase();
8412 AutoReadLock block(pBase COMMA_LOCKVAL_SRC_POS);
8413 fAutoReset = (pBase->m->type == MediumType_Immutable);
8414 }
8415 {
8416 AutoWriteLock tlock(pTarget COMMA_LOCKVAL_SRC_POS);
8417 pTarget->m->autoReset = fAutoReset;
8418 }
8419
8420 /* register with mVirtualBox as the last step and move to
8421 * Created state only on success (leaving an orphan file is
8422 * better than breaking media registry consistency) */
8423 ComObjPtr<Medium> pMedium;
8424 mrc = m->pVirtualBox->i_registerMedium(pTarget, &pMedium, treeLock);
8425 Assert(pTarget == pMedium);
8426
8427 if (FAILED(mrc))
8428 /* break the parent association on failure to register */
8429 i_deparent();
8430 }
8431
8432 AutoMultiWriteLock2 mediaLock(this, pTarget COMMA_LOCKVAL_SRC_POS);
8433
8434 if (SUCCEEDED(mrc))
8435 {
8436 pTarget->m->state = MediumState_Created;
8437
8438 pTarget->m->size = size;
8439 pTarget->m->logicalSize = logicalSize;
8440 pTarget->m->variant = variant;
8441 }
8442 else
8443 {
8444 /* back to NotCreated on failure */
8445 pTarget->m->state = MediumState_NotCreated;
8446
8447 pTarget->m->autoReset = false;
8448
8449 /* reset UUID to prevent it from being reused next time */
8450 if (fGenerateUuid)
8451 unconst(pTarget->m->id).clear();
8452 }
8453
8454 // deregister the task registered in createDiffStorage()
8455 Assert(m->numCreateDiffTasks != 0);
8456 --m->numCreateDiffTasks;
8457
8458 mediaLock.release();
8459 i_markRegistriesModified();
8460 if (task.isAsync())
8461 {
8462 // in asynchronous mode, save settings now
8463 m->pVirtualBox->i_saveModifiedRegistries();
8464 }
8465
8466 /* Note that in sync mode, it's the caller's responsibility to
8467 * unlock the medium. */
8468
8469 return mrc;
8470}
8471
8472/**
8473 * Implementation code for the "merge" task.
8474 *
8475 * This task always gets started from Medium::mergeTo() and can run
8476 * synchronously or asynchronously depending on the "wait" parameter passed to
8477 * that function. If we run synchronously, the caller expects the medium
8478 * registry modification to be set before returning; otherwise (in asynchronous
8479 * mode), we save the settings ourselves.
8480 *
8481 * @param task
8482 * @return
8483 */
8484HRESULT Medium::i_taskMergeHandler(Medium::MergeTask &task)
8485{
8486 /** @todo r=klaus The code below needs to be double checked with regard
8487 * to lock order violations, it probably causes lock order issues related
8488 * to the AutoCaller usage. */
8489 HRESULT rcTmp = S_OK;
8490
8491 const ComObjPtr<Medium> &pTarget = task.mTarget;
8492
8493 try
8494 {
8495 if (!task.mParentForTarget.isNull())
8496 if (task.mParentForTarget->i_getDepth() >= SETTINGS_MEDIUM_DEPTH_MAX)
8497 {
8498 AutoReadLock plock(task.mParentForTarget COMMA_LOCKVAL_SRC_POS);
8499 throw setError(VBOX_E_INVALID_OBJECT_STATE,
8500 tr("Cannot merge image for medium '%s', because it exceeds the medium tree depth limit. Please merge some images which you no longer need"),
8501 task.mParentForTarget->m->strLocationFull.c_str());
8502 }
8503
8504 PVDISK hdd;
8505 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
8506 ComAssertRCThrow(vrc, E_FAIL);
8507
8508 try
8509 {
8510 // Similar code appears in SessionMachine::onlineMergeMedium, so
8511 // if you make any changes below check whether they are applicable
8512 // in that context as well.
8513
8514 unsigned uTargetIdx = VD_LAST_IMAGE;
8515 unsigned uSourceIdx = VD_LAST_IMAGE;
8516 /* Open all media in the chain. */
8517 MediumLockList::Base::iterator lockListBegin =
8518 task.mpMediumLockList->GetBegin();
8519 MediumLockList::Base::iterator lockListEnd =
8520 task.mpMediumLockList->GetEnd();
8521 unsigned i = 0;
8522 for (MediumLockList::Base::iterator it = lockListBegin;
8523 it != lockListEnd;
8524 ++it)
8525 {
8526 MediumLock &mediumLock = *it;
8527 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
8528
8529 if (pMedium == this)
8530 uSourceIdx = i;
8531 else if (pMedium == pTarget)
8532 uTargetIdx = i;
8533
8534 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
8535
8536 /*
8537 * complex sanity (sane complexity)
8538 *
8539 * The current medium must be in the Deleting (medium is merged)
8540 * or LockedRead (parent medium) state if it is not the target.
8541 * If it is the target it must be in the LockedWrite state.
8542 */
8543 Assert( ( pMedium != pTarget
8544 && ( pMedium->m->state == MediumState_Deleting
8545 || pMedium->m->state == MediumState_LockedRead))
8546 || ( pMedium == pTarget
8547 && pMedium->m->state == MediumState_LockedWrite));
8548 /*
8549 * Medium must be the target, in the LockedRead state
8550 * or Deleting state where it is not allowed to be attached
8551 * to a virtual machine.
8552 */
8553 Assert( pMedium == pTarget
8554 || pMedium->m->state == MediumState_LockedRead
8555 || ( pMedium->m->backRefs.size() == 0
8556 && pMedium->m->state == MediumState_Deleting));
8557 /* The source medium must be in Deleting state. */
8558 Assert( pMedium != this
8559 || pMedium->m->state == MediumState_Deleting);
8560
8561 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
8562
8563 if ( pMedium->m->state == MediumState_LockedRead
8564 || pMedium->m->state == MediumState_Deleting)
8565 uOpenFlags = VD_OPEN_FLAGS_READONLY;
8566 if (pMedium->m->type == MediumType_Shareable)
8567 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
8568
8569 /* Open the medium */
8570 vrc = VDOpen(hdd,
8571 pMedium->m->strFormat.c_str(),
8572 pMedium->m->strLocationFull.c_str(),
8573 uOpenFlags | m->uOpenFlagsDef,
8574 pMedium->m->vdImageIfaces);
8575 if (RT_FAILURE(vrc))
8576 throw vrc;
8577
8578 i++;
8579 }
8580
8581 ComAssertThrow( uSourceIdx != VD_LAST_IMAGE
8582 && uTargetIdx != VD_LAST_IMAGE, E_FAIL);
8583
8584 vrc = VDMerge(hdd, uSourceIdx, uTargetIdx,
8585 task.mVDOperationIfaces);
8586 if (RT_FAILURE(vrc))
8587 throw vrc;
8588
8589 /* update parent UUIDs */
8590 if (!task.mfMergeForward)
8591 {
8592 /* we need to update UUIDs of all source's children
8593 * which cannot be part of the container at once so
8594 * add each one in there individually */
8595 if (task.mpChildrenToReparent)
8596 {
8597 MediumLockList::Base::iterator childrenBegin = task.mpChildrenToReparent->GetBegin();
8598 MediumLockList::Base::iterator childrenEnd = task.mpChildrenToReparent->GetEnd();
8599 for (MediumLockList::Base::iterator it = childrenBegin;
8600 it != childrenEnd;
8601 ++it)
8602 {
8603 Medium *pMedium = it->GetMedium();
8604 /* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
8605 vrc = VDOpen(hdd,
8606 pMedium->m->strFormat.c_str(),
8607 pMedium->m->strLocationFull.c_str(),
8608 VD_OPEN_FLAGS_INFO | m->uOpenFlagsDef,
8609 pMedium->m->vdImageIfaces);
8610 if (RT_FAILURE(vrc))
8611 throw vrc;
8612
8613 vrc = VDSetParentUuid(hdd, VD_LAST_IMAGE,
8614 pTarget->m->id.raw());
8615 if (RT_FAILURE(vrc))
8616 throw vrc;
8617
8618 vrc = VDClose(hdd, false /* fDelete */);
8619 if (RT_FAILURE(vrc))
8620 throw vrc;
8621 }
8622 }
8623 }
8624 }
8625 catch (HRESULT aRC) { rcTmp = aRC; }
8626 catch (int aVRC)
8627 {
8628 rcTmp = setError(VBOX_E_FILE_ERROR,
8629 tr("Could not merge the medium '%s' to '%s'%s"),
8630 m->strLocationFull.c_str(),
8631 pTarget->m->strLocationFull.c_str(),
8632 i_vdError(aVRC).c_str());
8633 }
8634
8635 VDDestroy(hdd);
8636 }
8637 catch (HRESULT aRC) { rcTmp = aRC; }
8638
8639 ErrorInfoKeeper eik;
8640 MultiResult mrc(rcTmp);
8641 HRESULT rc2;
8642
8643 if (SUCCEEDED(mrc))
8644 {
8645 /* all media but the target were successfully deleted by
8646 * VDMerge; reparent the last one and uninitialize deleted media. */
8647
8648 AutoWriteLock treeLock(m->pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
8649
8650 if (task.mfMergeForward)
8651 {
8652 /* first, unregister the target since it may become a base
8653 * medium which needs re-registration */
8654 rc2 = m->pVirtualBox->i_unregisterMedium(pTarget);
8655 AssertComRC(rc2);
8656
8657 /* then, reparent it and disconnect the deleted branch at both ends
8658 * (chain->parent() is source's parent). Depth check above. */
8659 pTarget->i_deparent();
8660 pTarget->i_setParent(task.mParentForTarget);
8661 if (task.mParentForTarget)
8662 i_deparent();
8663
8664 /* then, register again */
8665 ComObjPtr<Medium> pMedium;
8666 rc2 = m->pVirtualBox->i_registerMedium(pTarget, &pMedium,
8667 treeLock);
8668 AssertComRC(rc2);
8669 }
8670 else
8671 {
8672 Assert(pTarget->i_getChildren().size() == 1);
8673 Medium *targetChild = pTarget->i_getChildren().front();
8674
8675 /* disconnect the deleted branch at the elder end */
8676 targetChild->i_deparent();
8677
8678 /* reparent source's children and disconnect the deleted
8679 * branch at the younger end */
8680 if (task.mpChildrenToReparent)
8681 {
8682 /* obey {parent,child} lock order */
8683 AutoWriteLock sourceLock(this COMMA_LOCKVAL_SRC_POS);
8684
8685 MediumLockList::Base::iterator childrenBegin = task.mpChildrenToReparent->GetBegin();
8686 MediumLockList::Base::iterator childrenEnd = task.mpChildrenToReparent->GetEnd();
8687 for (MediumLockList::Base::iterator it = childrenBegin;
8688 it != childrenEnd;
8689 ++it)
8690 {
8691 Medium *pMedium = it->GetMedium();
8692 AutoWriteLock childLock(pMedium COMMA_LOCKVAL_SRC_POS);
8693
8694 pMedium->i_deparent(); // removes pMedium from source
8695 // no depth check, reduces depth
8696 pMedium->i_setParent(pTarget);
8697 }
8698 }
8699 }
8700
8701 /* unregister and uninitialize all media removed by the merge */
8702 MediumLockList::Base::iterator lockListBegin =
8703 task.mpMediumLockList->GetBegin();
8704 MediumLockList::Base::iterator lockListEnd =
8705 task.mpMediumLockList->GetEnd();
8706 for (MediumLockList::Base::iterator it = lockListBegin;
8707 it != lockListEnd;
8708 )
8709 {
8710 MediumLock &mediumLock = *it;
8711 /* Create a real copy of the medium pointer, as the medium
8712 * lock deletion below would invalidate the referenced object. */
8713 const ComObjPtr<Medium> pMedium = mediumLock.GetMedium();
8714
8715 /* The target and all media not merged (readonly) are skipped */
8716 if ( pMedium == pTarget
8717 || pMedium->m->state == MediumState_LockedRead)
8718 {
8719 ++it;
8720 continue;
8721 }
8722
8723 rc2 = pMedium->m->pVirtualBox->i_unregisterMedium(pMedium);
8724 AssertComRC(rc2);
8725
8726 /* now, uninitialize the deleted medium (note that
8727 * due to the Deleting state, uninit() will not touch
8728 * the parent-child relationship so we need to
8729 * uninitialize each disk individually) */
8730
8731 /* note that the operation initiator medium (which is
8732 * normally also the source medium) is a special case
8733 * -- there is one more caller added by Task to it which
8734 * we must release. Also, if we are in sync mode, the
8735 * caller may still hold an AutoCaller instance for it
8736 * and therefore we cannot uninit() it (it's therefore
8737 * the caller's responsibility) */
8738 if (pMedium == this)
8739 {
8740 Assert(i_getChildren().size() == 0);
8741 Assert(m->backRefs.size() == 0);
8742 task.mMediumCaller.release();
8743 }
8744
8745 /* Delete the medium lock list entry, which also releases the
8746 * caller added by MergeChain before uninit() and updates the
8747 * iterator to point to the right place. */
8748 rc2 = task.mpMediumLockList->RemoveByIterator(it);
8749 AssertComRC(rc2);
8750
8751 if (task.isAsync() || pMedium != this)
8752 {
8753 treeLock.release();
8754 pMedium->uninit();
8755 treeLock.acquire();
8756 }
8757 }
8758 }
8759
8760 i_markRegistriesModified();
8761 if (task.isAsync())
8762 {
8763 // in asynchronous mode, save settings now
8764 eik.restore();
8765 m->pVirtualBox->i_saveModifiedRegistries();
8766 eik.fetch();
8767 }
8768
8769 if (FAILED(mrc))
8770 {
8771 /* Here we come if either VDMerge() failed (in which case we
8772 * assume that it tried to do everything to make a further
8773 * retry possible -- e.g. not deleted intermediate media
8774 * and so on) or VirtualBox::saveRegistries() failed (where we
8775 * should have the original tree but with intermediate storage
8776 * units deleted by VDMerge()). We have to only restore states
8777 * (through the MergeChain dtor) unless we are run synchronously
8778 * in which case it's the responsibility of the caller as stated
8779 * in the mergeTo() docs. The latter also implies that we
8780 * don't own the merge chain, so release it in this case. */
8781 if (task.isAsync())
8782 i_cancelMergeTo(task.mpChildrenToReparent, task.mpMediumLockList);
8783 }
8784
8785 return mrc;
8786}
8787
8788/**
8789 * Implementation code for the "clone" task.
8790 *
8791 * This only gets started from Medium::CloneTo() and always runs asynchronously.
8792 * As a result, we always save the VirtualBox.xml file when we're done here.
8793 *
8794 * @param task
8795 * @return
8796 */
8797HRESULT Medium::i_taskCloneHandler(Medium::CloneTask &task)
8798{
8799 /** @todo r=klaus The code below needs to be double checked with regard
8800 * to lock order violations, it probably causes lock order issues related
8801 * to the AutoCaller usage. */
8802 HRESULT rcTmp = S_OK;
8803
8804 const ComObjPtr<Medium> &pTarget = task.mTarget;
8805 const ComObjPtr<Medium> &pParent = task.mParent;
8806
8807 bool fCreatingTarget = false;
8808
8809 uint64_t size = 0, logicalSize = 0;
8810 MediumVariant_T variant = MediumVariant_Standard;
8811 bool fGenerateUuid = false;
8812
8813 try
8814 {
8815 if (!pParent.isNull())
8816 {
8817
8818 if (pParent->i_getDepth() >= SETTINGS_MEDIUM_DEPTH_MAX)
8819 {
8820 AutoReadLock plock(pParent COMMA_LOCKVAL_SRC_POS);
8821 throw setError(VBOX_E_INVALID_OBJECT_STATE,
8822 tr("Cannot clone image for medium '%s', because it exceeds the medium tree depth limit. Please merge some images which you no longer need"),
8823 pParent->m->strLocationFull.c_str());
8824 }
8825 }
8826
8827 /* Lock all in {parent,child} order. The lock is also used as a
8828 * signal from the task initiator (which releases it only after
8829 * RTThreadCreate()) that we can start the job. */
8830 AutoMultiWriteLock3 thisLock(this, pTarget, pParent COMMA_LOCKVAL_SRC_POS);
8831
8832 fCreatingTarget = pTarget->m->state == MediumState_Creating;
8833
8834 /* The object may request a specific UUID (through a special form of
8835 * the setLocation() argument). Otherwise we have to generate it */
8836 Guid targetId = pTarget->m->id;
8837
8838 fGenerateUuid = targetId.isZero();
8839 if (fGenerateUuid)
8840 {
8841 targetId.create();
8842 /* VirtualBox::registerMedium() will need UUID */
8843 unconst(pTarget->m->id) = targetId;
8844 }
8845
8846 PVDISK hdd;
8847 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
8848 ComAssertRCThrow(vrc, E_FAIL);
8849
8850 try
8851 {
8852 /* Open all media in the source chain. */
8853 MediumLockList::Base::const_iterator sourceListBegin =
8854 task.mpSourceMediumLockList->GetBegin();
8855 MediumLockList::Base::const_iterator sourceListEnd =
8856 task.mpSourceMediumLockList->GetEnd();
8857 for (MediumLockList::Base::const_iterator it = sourceListBegin;
8858 it != sourceListEnd;
8859 ++it)
8860 {
8861 const MediumLock &mediumLock = *it;
8862 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
8863 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
8864
8865 /* sanity check */
8866 Assert(pMedium->m->state == MediumState_LockedRead);
8867
8868 /** Open all media in read-only mode. */
8869 vrc = VDOpen(hdd,
8870 pMedium->m->strFormat.c_str(),
8871 pMedium->m->strLocationFull.c_str(),
8872 VD_OPEN_FLAGS_READONLY | m->uOpenFlagsDef,
8873 pMedium->m->vdImageIfaces);
8874 if (RT_FAILURE(vrc))
8875 throw setError(VBOX_E_FILE_ERROR,
8876 tr("Could not open the medium storage unit '%s'%s"),
8877 pMedium->m->strLocationFull.c_str(),
8878 i_vdError(vrc).c_str());
8879 }
8880
8881 Utf8Str targetFormat(pTarget->m->strFormat);
8882 Utf8Str targetLocation(pTarget->m->strLocationFull);
8883 uint64_t capabilities = pTarget->m->formatObj->i_getCapabilities();
8884
8885 Assert( pTarget->m->state == MediumState_Creating
8886 || pTarget->m->state == MediumState_LockedWrite);
8887 Assert(m->state == MediumState_LockedRead);
8888 Assert( pParent.isNull()
8889 || pParent->m->state == MediumState_LockedRead);
8890
8891 /* unlock before the potentially lengthy operation */
8892 thisLock.release();
8893
8894 /* ensure the target directory exists */
8895 if (capabilities & MediumFormatCapabilities_File)
8896 {
8897 HRESULT rc = VirtualBox::i_ensureFilePathExists(targetLocation,
8898 !(task.mVariant & MediumVariant_NoCreateDir) /* fCreate */);
8899 if (FAILED(rc))
8900 throw rc;
8901 }
8902
8903 PVDISK targetHdd;
8904 vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &targetHdd);
8905 ComAssertRCThrow(vrc, E_FAIL);
8906
8907 try
8908 {
8909 /* Open all media in the target chain. */
8910 MediumLockList::Base::const_iterator targetListBegin =
8911 task.mpTargetMediumLockList->GetBegin();
8912 MediumLockList::Base::const_iterator targetListEnd =
8913 task.mpTargetMediumLockList->GetEnd();
8914 for (MediumLockList::Base::const_iterator it = targetListBegin;
8915 it != targetListEnd;
8916 ++it)
8917 {
8918 const MediumLock &mediumLock = *it;
8919 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
8920
8921 /* If the target medium is not created yet there's no
8922 * reason to open it. */
8923 if (pMedium == pTarget && fCreatingTarget)
8924 continue;
8925
8926 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
8927
8928 /* sanity check */
8929 Assert( pMedium->m->state == MediumState_LockedRead
8930 || pMedium->m->state == MediumState_LockedWrite);
8931
8932 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
8933 if (pMedium->m->state != MediumState_LockedWrite)
8934 uOpenFlags = VD_OPEN_FLAGS_READONLY;
8935 if (pMedium->m->type == MediumType_Shareable)
8936 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
8937
8938 /* Open all media in appropriate mode. */
8939 vrc = VDOpen(targetHdd,
8940 pMedium->m->strFormat.c_str(),
8941 pMedium->m->strLocationFull.c_str(),
8942 uOpenFlags | m->uOpenFlagsDef,
8943 pMedium->m->vdImageIfaces);
8944 if (RT_FAILURE(vrc))
8945 throw setError(VBOX_E_FILE_ERROR,
8946 tr("Could not open the medium storage unit '%s'%s"),
8947 pMedium->m->strLocationFull.c_str(),
8948 i_vdError(vrc).c_str());
8949 }
8950
8951 /* target isn't locked, but no changing data is accessed */
8952 if (task.midxSrcImageSame == UINT32_MAX)
8953 {
8954 vrc = VDCopy(hdd,
8955 VD_LAST_IMAGE,
8956 targetHdd,
8957 targetFormat.c_str(),
8958 (fCreatingTarget) ? targetLocation.c_str() : (char *)NULL,
8959 false /* fMoveByRename */,
8960 0 /* cbSize */,
8961 task.mVariant & ~MediumVariant_NoCreateDir,
8962 targetId.raw(),
8963 VD_OPEN_FLAGS_NORMAL | m->uOpenFlagsDef,
8964 NULL /* pVDIfsOperation */,
8965 pTarget->m->vdImageIfaces,
8966 task.mVDOperationIfaces);
8967 }
8968 else
8969 {
8970 vrc = VDCopyEx(hdd,
8971 VD_LAST_IMAGE,
8972 targetHdd,
8973 targetFormat.c_str(),
8974 (fCreatingTarget) ? targetLocation.c_str() : (char *)NULL,
8975 false /* fMoveByRename */,
8976 0 /* cbSize */,
8977 task.midxSrcImageSame,
8978 task.midxDstImageSame,
8979 task.mVariant & ~MediumVariant_NoCreateDir,
8980 targetId.raw(),
8981 VD_OPEN_FLAGS_NORMAL | m->uOpenFlagsDef,
8982 NULL /* pVDIfsOperation */,
8983 pTarget->m->vdImageIfaces,
8984 task.mVDOperationIfaces);
8985 }
8986 if (RT_FAILURE(vrc))
8987 throw setError(VBOX_E_FILE_ERROR,
8988 tr("Could not create the clone medium '%s'%s"),
8989 targetLocation.c_str(), i_vdError(vrc).c_str());
8990
8991 size = VDGetFileSize(targetHdd, VD_LAST_IMAGE);
8992 logicalSize = VDGetSize(targetHdd, VD_LAST_IMAGE);
8993 unsigned uImageFlags;
8994 vrc = VDGetImageFlags(targetHdd, 0, &uImageFlags);
8995 if (RT_SUCCESS(vrc))
8996 variant = (MediumVariant_T)uImageFlags;
8997 }
8998 catch (HRESULT aRC) { rcTmp = aRC; }
8999
9000 VDDestroy(targetHdd);
9001 }
9002 catch (HRESULT aRC) { rcTmp = aRC; }
9003
9004 VDDestroy(hdd);
9005 }
9006 catch (HRESULT aRC) { rcTmp = aRC; }
9007
9008 ErrorInfoKeeper eik;
9009 MultiResult mrc(rcTmp);
9010
9011 /* Only do the parent changes for newly created media. */
9012 if (SUCCEEDED(mrc) && fCreatingTarget)
9013 {
9014 /* we set m->pParent & children() */
9015 AutoWriteLock treeLock(m->pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
9016
9017 Assert(pTarget->m->pParent.isNull());
9018
9019 if (pParent)
9020 {
9021 /* Associate the clone with the parent and deassociate
9022 * from VirtualBox. Depth check above. */
9023 pTarget->i_setParent(pParent);
9024
9025 /* register with mVirtualBox as the last step and move to
9026 * Created state only on success (leaving an orphan file is
9027 * better than breaking media registry consistency) */
9028 eik.restore();
9029 ComObjPtr<Medium> pMedium;
9030 mrc = pParent->m->pVirtualBox->i_registerMedium(pTarget, &pMedium,
9031 treeLock);
9032 Assert( FAILED(mrc)
9033 || pTarget == pMedium);
9034 eik.fetch();
9035
9036 if (FAILED(mrc))
9037 /* break parent association on failure to register */
9038 pTarget->i_deparent(); // removes target from parent
9039 }
9040 else
9041 {
9042 /* just register */
9043 eik.restore();
9044 ComObjPtr<Medium> pMedium;
9045 mrc = m->pVirtualBox->i_registerMedium(pTarget, &pMedium,
9046 treeLock);
9047 Assert( FAILED(mrc)
9048 || pTarget == pMedium);
9049 eik.fetch();
9050 }
9051 }
9052
9053 if (fCreatingTarget)
9054 {
9055 AutoWriteLock mLock(pTarget COMMA_LOCKVAL_SRC_POS);
9056
9057 if (SUCCEEDED(mrc))
9058 {
9059 pTarget->m->state = MediumState_Created;
9060
9061 pTarget->m->size = size;
9062 pTarget->m->logicalSize = logicalSize;
9063 pTarget->m->variant = variant;
9064 }
9065 else
9066 {
9067 /* back to NotCreated on failure */
9068 pTarget->m->state = MediumState_NotCreated;
9069
9070 /* reset UUID to prevent it from being reused next time */
9071 if (fGenerateUuid)
9072 unconst(pTarget->m->id).clear();
9073 }
9074 }
9075
9076 /* Copy any filter related settings over to the target. */
9077 if (SUCCEEDED(mrc))
9078 {
9079 /* Copy any filter related settings over. */
9080 ComObjPtr<Medium> pBase = i_getBase();
9081 ComObjPtr<Medium> pTargetBase = pTarget->i_getBase();
9082 std::vector<com::Utf8Str> aFilterPropNames;
9083 std::vector<com::Utf8Str> aFilterPropValues;
9084 mrc = pBase->i_getFilterProperties(aFilterPropNames, aFilterPropValues);
9085 if (SUCCEEDED(mrc))
9086 {
9087 /* Go through the properties and add them to the target medium. */
9088 for (unsigned idx = 0; idx < aFilterPropNames.size(); idx++)
9089 {
9090 mrc = pTargetBase->i_setPropertyDirect(aFilterPropNames[idx], aFilterPropValues[idx]);
9091 if (FAILED(mrc)) break;
9092 }
9093
9094 // now, at the end of this task (always asynchronous), save the settings
9095 if (SUCCEEDED(mrc))
9096 {
9097 // save the settings
9098 i_markRegistriesModified();
9099 /* collect multiple errors */
9100 eik.restore();
9101 m->pVirtualBox->i_saveModifiedRegistries();
9102 eik.fetch();
9103 }
9104 }
9105 }
9106
9107 /* Everything is explicitly unlocked when the task exits,
9108 * as the task destruction also destroys the source chain. */
9109
9110 /* Make sure the source chain is released early. It could happen
9111 * that we get a deadlock in Appliance::Import when Medium::Close
9112 * is called & the source chain is released at the same time. */
9113 task.mpSourceMediumLockList->Clear();
9114
9115 return mrc;
9116}
9117
9118/**
9119 * Implementation code for the "move" task.
9120 *
9121 * This only gets started from Medium::SetLocation() and always
9122 * runs asynchronously.
9123 *
9124 * @param task
9125 * @return
9126 */
9127HRESULT Medium::i_taskMoveHandler(Medium::MoveTask &task)
9128{
9129
9130 HRESULT rcOut = S_OK;
9131
9132 /* pTarget is equal "this" in our case */
9133 const ComObjPtr<Medium> &pTarget = task.mMedium;
9134
9135 uint64_t size = 0; NOREF(size);
9136 uint64_t logicalSize = 0; NOREF(logicalSize);
9137 MediumVariant_T variant = MediumVariant_Standard; NOREF(variant);
9138
9139 /*
9140 * it's exactly moving, not cloning
9141 */
9142 if (!i_isMoveOperation(pTarget))
9143 {
9144 HRESULT rc = setError(VBOX_E_FILE_ERROR,
9145 tr("Wrong preconditions for moving the medium %s"),
9146 pTarget->m->strLocationFull.c_str());
9147 return rc;
9148 }
9149
9150 try
9151 {
9152 /* Lock all in {parent,child} order. The lock is also used as a
9153 * signal from the task initiator (which releases it only after
9154 * RTThreadCreate()) that we can start the job. */
9155
9156 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
9157
9158 PVDISK hdd;
9159 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
9160 ComAssertRCThrow(vrc, E_FAIL);
9161
9162 try
9163 {
9164 /* Open all media in the source chain. */
9165 MediumLockList::Base::const_iterator sourceListBegin =
9166 task.mpMediumLockList->GetBegin();
9167 MediumLockList::Base::const_iterator sourceListEnd =
9168 task.mpMediumLockList->GetEnd();
9169 for (MediumLockList::Base::const_iterator it = sourceListBegin;
9170 it != sourceListEnd;
9171 ++it)
9172 {
9173 const MediumLock &mediumLock = *it;
9174 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
9175 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
9176
9177 /* sanity check */
9178 Assert(pMedium->m->state == MediumState_LockedWrite);
9179
9180 vrc = VDOpen(hdd,
9181 pMedium->m->strFormat.c_str(),
9182 pMedium->m->strLocationFull.c_str(),
9183 VD_OPEN_FLAGS_NORMAL,
9184 pMedium->m->vdImageIfaces);
9185 if (RT_FAILURE(vrc))
9186 throw setError(VBOX_E_FILE_ERROR,
9187 tr("Could not open the medium storage unit '%s'%s"),
9188 pMedium->m->strLocationFull.c_str(),
9189 i_vdError(vrc).c_str());
9190 }
9191
9192 /* we can directly use pTarget->m->"variables" but for better reading we use local copies */
9193 Guid targetId = pTarget->m->id;
9194 Utf8Str targetFormat(pTarget->m->strFormat);
9195 uint64_t targetCapabilities = pTarget->m->formatObj->i_getCapabilities();
9196
9197 /*
9198 * change target location
9199 * m->strNewLocationFull has been set already together with m->fMoveThisMedium in
9200 * i_preparationForMoving()
9201 */
9202 Utf8Str targetLocation = i_getNewLocationForMoving();
9203
9204 /* unlock before the potentially lengthy operation */
9205 thisLock.release();
9206
9207 /* ensure the target directory exists */
9208 if (targetCapabilities & MediumFormatCapabilities_File)
9209 {
9210 HRESULT rc = VirtualBox::i_ensureFilePathExists(targetLocation,
9211 !(task.mVariant & MediumVariant_NoCreateDir) /* fCreate */);
9212 if (FAILED(rc))
9213 throw rc;
9214 }
9215
9216 try
9217 {
9218 vrc = VDCopy(hdd,
9219 VD_LAST_IMAGE,
9220 hdd,
9221 targetFormat.c_str(),
9222 targetLocation.c_str(),
9223 true /* fMoveByRename */,
9224 0 /* cbSize */,
9225 VD_IMAGE_FLAGS_NONE,
9226 targetId.raw(),
9227 VD_OPEN_FLAGS_NORMAL,
9228 NULL /* pVDIfsOperation */,
9229 NULL,
9230 NULL);
9231 if (RT_FAILURE(vrc))
9232 throw setError(VBOX_E_FILE_ERROR,
9233 tr("Could not move medium '%s'%s"),
9234 targetLocation.c_str(), i_vdError(vrc).c_str());
9235 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
9236 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE);
9237 unsigned uImageFlags;
9238 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
9239 if (RT_SUCCESS(vrc))
9240 variant = (MediumVariant_T)uImageFlags;
9241
9242 /*
9243 * set current location, because VDCopy\VDCopyEx doesn't do it.
9244 * also reset moving flag
9245 */
9246 i_resetMoveOperationData();
9247 m->strLocationFull = targetLocation;
9248
9249 }
9250 catch (HRESULT aRC) { rcOut = aRC; }
9251
9252 }
9253 catch (HRESULT aRC) { rcOut = aRC; }
9254
9255 VDDestroy(hdd);
9256 }
9257 catch (HRESULT aRC) { rcOut = aRC; }
9258
9259 ErrorInfoKeeper eik;
9260 MultiResult mrc(rcOut);
9261
9262 // now, at the end of this task (always asynchronous), save the settings
9263 if (SUCCEEDED(mrc))
9264 {
9265 // save the settings
9266 i_markRegistriesModified();
9267 /* collect multiple errors */
9268 eik.restore();
9269 m->pVirtualBox->i_saveModifiedRegistries();
9270 eik.fetch();
9271 }
9272
9273 /* Everything is explicitly unlocked when the task exits,
9274 * as the task destruction also destroys the source chain. */
9275
9276 task.mpMediumLockList->Clear();
9277
9278 return mrc;
9279}
9280
9281/**
9282 * Implementation code for the "delete" task.
9283 *
9284 * This task always gets started from Medium::deleteStorage() and can run
9285 * synchronously or asynchronously depending on the "wait" parameter passed to
9286 * that function.
9287 *
9288 * @param task
9289 * @return
9290 */
9291HRESULT Medium::i_taskDeleteHandler(Medium::DeleteTask &task)
9292{
9293 NOREF(task);
9294 HRESULT rc = S_OK;
9295
9296 try
9297 {
9298 /* The lock is also used as a signal from the task initiator (which
9299 * releases it only after RTThreadCreate()) that we can start the job */
9300 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
9301
9302 PVDISK hdd;
9303 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
9304 ComAssertRCThrow(vrc, E_FAIL);
9305
9306 Utf8Str format(m->strFormat);
9307 Utf8Str location(m->strLocationFull);
9308
9309 /* unlock before the potentially lengthy operation */
9310 Assert(m->state == MediumState_Deleting);
9311 thisLock.release();
9312
9313 try
9314 {
9315 vrc = VDOpen(hdd,
9316 format.c_str(),
9317 location.c_str(),
9318 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO | m->uOpenFlagsDef,
9319 m->vdImageIfaces);
9320 if (RT_SUCCESS(vrc))
9321 vrc = VDClose(hdd, true /* fDelete */);
9322
9323 if (RT_FAILURE(vrc))
9324 throw setError(VBOX_E_FILE_ERROR,
9325 tr("Could not delete the medium storage unit '%s'%s"),
9326 location.c_str(), i_vdError(vrc).c_str());
9327
9328 }
9329 catch (HRESULT aRC) { rc = aRC; }
9330
9331 VDDestroy(hdd);
9332 }
9333 catch (HRESULT aRC) { rc = aRC; }
9334
9335 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
9336
9337 /* go to the NotCreated state even on failure since the storage
9338 * may have been already partially deleted and cannot be used any
9339 * more. One will be able to manually re-open the storage if really
9340 * needed to re-register it. */
9341 m->state = MediumState_NotCreated;
9342
9343 /* Reset UUID to prevent Create* from reusing it again */
9344 unconst(m->id).clear();
9345
9346 return rc;
9347}
9348
9349/**
9350 * Implementation code for the "reset" task.
9351 *
9352 * This always gets started asynchronously from Medium::Reset().
9353 *
9354 * @param task
9355 * @return
9356 */
9357HRESULT Medium::i_taskResetHandler(Medium::ResetTask &task)
9358{
9359 HRESULT rc = S_OK;
9360
9361 uint64_t size = 0, logicalSize = 0;
9362 MediumVariant_T variant = MediumVariant_Standard;
9363
9364 try
9365 {
9366 /* The lock is also used as a signal from the task initiator (which
9367 * releases it only after RTThreadCreate()) that we can start the job */
9368 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
9369
9370 /// @todo Below we use a pair of delete/create operations to reset
9371 /// the diff contents but the most efficient way will of course be
9372 /// to add a VDResetDiff() API call
9373
9374 PVDISK hdd;
9375 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
9376 ComAssertRCThrow(vrc, E_FAIL);
9377
9378 Guid id = m->id;
9379 Utf8Str format(m->strFormat);
9380 Utf8Str location(m->strLocationFull);
9381
9382 Medium *pParent = m->pParent;
9383 Guid parentId = pParent->m->id;
9384 Utf8Str parentFormat(pParent->m->strFormat);
9385 Utf8Str parentLocation(pParent->m->strLocationFull);
9386
9387 Assert(m->state == MediumState_LockedWrite);
9388
9389 /* unlock before the potentially lengthy operation */
9390 thisLock.release();
9391
9392 try
9393 {
9394 /* Open all media in the target chain but the last. */
9395 MediumLockList::Base::const_iterator targetListBegin =
9396 task.mpMediumLockList->GetBegin();
9397 MediumLockList::Base::const_iterator targetListEnd =
9398 task.mpMediumLockList->GetEnd();
9399 for (MediumLockList::Base::const_iterator it = targetListBegin;
9400 it != targetListEnd;
9401 ++it)
9402 {
9403 const MediumLock &mediumLock = *it;
9404 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
9405
9406 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
9407
9408 /* sanity check, "this" is checked above */
9409 Assert( pMedium == this
9410 || pMedium->m->state == MediumState_LockedRead);
9411
9412 /* Open all media in appropriate mode. */
9413 vrc = VDOpen(hdd,
9414 pMedium->m->strFormat.c_str(),
9415 pMedium->m->strLocationFull.c_str(),
9416 VD_OPEN_FLAGS_READONLY | m->uOpenFlagsDef,
9417 pMedium->m->vdImageIfaces);
9418 if (RT_FAILURE(vrc))
9419 throw setError(VBOX_E_FILE_ERROR,
9420 tr("Could not open the medium storage unit '%s'%s"),
9421 pMedium->m->strLocationFull.c_str(),
9422 i_vdError(vrc).c_str());
9423
9424 /* Done when we hit the media which should be reset */
9425 if (pMedium == this)
9426 break;
9427 }
9428
9429 /* first, delete the storage unit */
9430 vrc = VDClose(hdd, true /* fDelete */);
9431 if (RT_FAILURE(vrc))
9432 throw setError(VBOX_E_FILE_ERROR,
9433 tr("Could not delete the medium storage unit '%s'%s"),
9434 location.c_str(), i_vdError(vrc).c_str());
9435
9436 /* next, create it again */
9437 vrc = VDOpen(hdd,
9438 parentFormat.c_str(),
9439 parentLocation.c_str(),
9440 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO | m->uOpenFlagsDef,
9441 m->vdImageIfaces);
9442 if (RT_FAILURE(vrc))
9443 throw setError(VBOX_E_FILE_ERROR,
9444 tr("Could not open the medium storage unit '%s'%s"),
9445 parentLocation.c_str(), i_vdError(vrc).c_str());
9446
9447 vrc = VDCreateDiff(hdd,
9448 format.c_str(),
9449 location.c_str(),
9450 /// @todo use the same medium variant as before
9451 VD_IMAGE_FLAGS_NONE,
9452 NULL,
9453 id.raw(),
9454 parentId.raw(),
9455 VD_OPEN_FLAGS_NORMAL,
9456 m->vdImageIfaces,
9457 task.mVDOperationIfaces);
9458 if (RT_FAILURE(vrc))
9459 {
9460 if (vrc == VERR_VD_INVALID_TYPE)
9461 throw setError(VBOX_E_FILE_ERROR,
9462 tr("Parameters for creating the differencing medium storage unit '%s' are invalid%s"),
9463 location.c_str(), i_vdError(vrc).c_str());
9464 else
9465 throw setError(VBOX_E_FILE_ERROR,
9466 tr("Could not create the differencing medium storage unit '%s'%s"),
9467 location.c_str(), i_vdError(vrc).c_str());
9468 }
9469
9470 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
9471 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE);
9472 unsigned uImageFlags;
9473 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
9474 if (RT_SUCCESS(vrc))
9475 variant = (MediumVariant_T)uImageFlags;
9476 }
9477 catch (HRESULT aRC) { rc = aRC; }
9478
9479 VDDestroy(hdd);
9480 }
9481 catch (HRESULT aRC) { rc = aRC; }
9482
9483 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
9484
9485 m->size = size;
9486 m->logicalSize = logicalSize;
9487 m->variant = variant;
9488
9489 /* Everything is explicitly unlocked when the task exits,
9490 * as the task destruction also destroys the media chain. */
9491
9492 return rc;
9493}
9494
9495/**
9496 * Implementation code for the "compact" task.
9497 *
9498 * @param task
9499 * @return
9500 */
9501HRESULT Medium::i_taskCompactHandler(Medium::CompactTask &task)
9502{
9503 HRESULT rc = S_OK;
9504
9505 /* Lock all in {parent,child} order. The lock is also used as a
9506 * signal from the task initiator (which releases it only after
9507 * RTThreadCreate()) that we can start the job. */
9508 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
9509
9510 try
9511 {
9512 PVDISK hdd;
9513 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
9514 ComAssertRCThrow(vrc, E_FAIL);
9515
9516 try
9517 {
9518 /* Open all media in the chain. */
9519 MediumLockList::Base::const_iterator mediumListBegin =
9520 task.mpMediumLockList->GetBegin();
9521 MediumLockList::Base::const_iterator mediumListEnd =
9522 task.mpMediumLockList->GetEnd();
9523 MediumLockList::Base::const_iterator mediumListLast =
9524 mediumListEnd;
9525 --mediumListLast;
9526 for (MediumLockList::Base::const_iterator it = mediumListBegin;
9527 it != mediumListEnd;
9528 ++it)
9529 {
9530 const MediumLock &mediumLock = *it;
9531 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
9532 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
9533
9534 /* sanity check */
9535 if (it == mediumListLast)
9536 Assert(pMedium->m->state == MediumState_LockedWrite);
9537 else
9538 Assert(pMedium->m->state == MediumState_LockedRead);
9539
9540 /* Open all media but last in read-only mode. Do not handle
9541 * shareable media, as compaction and sharing are mutually
9542 * exclusive. */
9543 vrc = VDOpen(hdd,
9544 pMedium->m->strFormat.c_str(),
9545 pMedium->m->strLocationFull.c_str(),
9546 m->uOpenFlagsDef | (it == mediumListLast ? VD_OPEN_FLAGS_NORMAL : VD_OPEN_FLAGS_READONLY),
9547 pMedium->m->vdImageIfaces);
9548 if (RT_FAILURE(vrc))
9549 throw setError(VBOX_E_FILE_ERROR,
9550 tr("Could not open the medium storage unit '%s'%s"),
9551 pMedium->m->strLocationFull.c_str(),
9552 i_vdError(vrc).c_str());
9553 }
9554
9555 Assert(m->state == MediumState_LockedWrite);
9556
9557 Utf8Str location(m->strLocationFull);
9558
9559 /* unlock before the potentially lengthy operation */
9560 thisLock.release();
9561
9562 vrc = VDCompact(hdd, VD_LAST_IMAGE, task.mVDOperationIfaces);
9563 if (RT_FAILURE(vrc))
9564 {
9565 if (vrc == VERR_NOT_SUPPORTED)
9566 throw setError(VBOX_E_NOT_SUPPORTED,
9567 tr("Compacting is not yet supported for medium '%s'"),
9568 location.c_str());
9569 else if (vrc == VERR_NOT_IMPLEMENTED)
9570 throw setError(E_NOTIMPL,
9571 tr("Compacting is not implemented, medium '%s'"),
9572 location.c_str());
9573 else
9574 throw setError(VBOX_E_FILE_ERROR,
9575 tr("Could not compact medium '%s'%s"),
9576 location.c_str(),
9577 i_vdError(vrc).c_str());
9578 }
9579 }
9580 catch (HRESULT aRC) { rc = aRC; }
9581
9582 VDDestroy(hdd);
9583 }
9584 catch (HRESULT aRC) { rc = aRC; }
9585
9586 /* Everything is explicitly unlocked when the task exits,
9587 * as the task destruction also destroys the media chain. */
9588
9589 return rc;
9590}
9591
9592/**
9593 * Implementation code for the "resize" task.
9594 *
9595 * @param task
9596 * @return
9597 */
9598HRESULT Medium::i_taskResizeHandler(Medium::ResizeTask &task)
9599{
9600 HRESULT rc = S_OK;
9601
9602 uint64_t size = 0, logicalSize = 0;
9603
9604 try
9605 {
9606 /* The lock is also used as a signal from the task initiator (which
9607 * releases it only after RTThreadCreate()) that we can start the job */
9608 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
9609
9610 PVDISK hdd;
9611 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
9612 ComAssertRCThrow(vrc, E_FAIL);
9613
9614 try
9615 {
9616 /* Open all media in the chain. */
9617 MediumLockList::Base::const_iterator mediumListBegin =
9618 task.mpMediumLockList->GetBegin();
9619 MediumLockList::Base::const_iterator mediumListEnd =
9620 task.mpMediumLockList->GetEnd();
9621 MediumLockList::Base::const_iterator mediumListLast =
9622 mediumListEnd;
9623 --mediumListLast;
9624 for (MediumLockList::Base::const_iterator it = mediumListBegin;
9625 it != mediumListEnd;
9626 ++it)
9627 {
9628 const MediumLock &mediumLock = *it;
9629 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
9630 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
9631
9632 /* sanity check */
9633 if (it == mediumListLast)
9634 Assert(pMedium->m->state == MediumState_LockedWrite);
9635 else
9636 Assert(pMedium->m->state == MediumState_LockedRead);
9637
9638 /* Open all media but last in read-only mode. Do not handle
9639 * shareable media, as compaction and sharing are mutually
9640 * exclusive. */
9641 vrc = VDOpen(hdd,
9642 pMedium->m->strFormat.c_str(),
9643 pMedium->m->strLocationFull.c_str(),
9644 m->uOpenFlagsDef | (it == mediumListLast ? VD_OPEN_FLAGS_NORMAL : VD_OPEN_FLAGS_READONLY),
9645 pMedium->m->vdImageIfaces);
9646 if (RT_FAILURE(vrc))
9647 throw setError(VBOX_E_FILE_ERROR,
9648 tr("Could not open the medium storage unit '%s'%s"),
9649 pMedium->m->strLocationFull.c_str(),
9650 i_vdError(vrc).c_str());
9651 }
9652
9653 Assert(m->state == MediumState_LockedWrite);
9654
9655 Utf8Str location(m->strLocationFull);
9656
9657 /* unlock before the potentially lengthy operation */
9658 thisLock.release();
9659
9660 VDGEOMETRY geo = {0, 0, 0}; /* auto */
9661 vrc = VDResize(hdd, task.mSize, &geo, &geo, task.mVDOperationIfaces);
9662 if (RT_FAILURE(vrc))
9663 {
9664 if (vrc == VERR_NOT_SUPPORTED)
9665 throw setError(VBOX_E_NOT_SUPPORTED,
9666 tr("Resizing to new size %llu is not yet supported for medium '%s'"),
9667 task.mSize, location.c_str());
9668 else if (vrc == VERR_NOT_IMPLEMENTED)
9669 throw setError(E_NOTIMPL,
9670 tr("Resiting is not implemented, medium '%s'"),
9671 location.c_str());
9672 else
9673 throw setError(VBOX_E_FILE_ERROR,
9674 tr("Could not resize medium '%s'%s"),
9675 location.c_str(),
9676 i_vdError(vrc).c_str());
9677 }
9678 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
9679 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE);
9680 }
9681 catch (HRESULT aRC) { rc = aRC; }
9682
9683 VDDestroy(hdd);
9684 }
9685 catch (HRESULT aRC) { rc = aRC; }
9686
9687 if (SUCCEEDED(rc))
9688 {
9689 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
9690 m->size = size;
9691 m->logicalSize = logicalSize;
9692 }
9693
9694 /* Everything is explicitly unlocked when the task exits,
9695 * as the task destruction also destroys the media chain. */
9696
9697 return rc;
9698}
9699
9700/**
9701 * Implementation code for the "export" task.
9702 *
9703 * This only gets started from Medium::exportFile() and always runs
9704 * asynchronously. It doesn't touch anything configuration related, so
9705 * we never save the VirtualBox.xml file here.
9706 *
9707 * @param task
9708 * @return
9709 */
9710HRESULT Medium::i_taskExportHandler(Medium::ExportTask &task)
9711{
9712 HRESULT rc = S_OK;
9713
9714 try
9715 {
9716 /* Lock all in {parent,child} order. The lock is also used as a
9717 * signal from the task initiator (which releases it only after
9718 * RTThreadCreate()) that we can start the job. */
9719 ComObjPtr<Medium> pBase = i_getBase();
9720 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
9721
9722 PVDISK hdd;
9723 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
9724 ComAssertRCThrow(vrc, E_FAIL);
9725
9726 try
9727 {
9728 settings::StringsMap::iterator itKeyStore = pBase->m->mapProperties.find("CRYPT/KeyStore");
9729 if (itKeyStore != pBase->m->mapProperties.end())
9730 {
9731 settings::StringsMap::iterator itKeyId = pBase->m->mapProperties.find("CRYPT/KeyId");
9732
9733#ifdef VBOX_WITH_EXTPACK
9734 ExtPackManager *pExtPackManager = m->pVirtualBox->i_getExtPackManager();
9735 if (pExtPackManager->i_isExtPackUsable(ORACLE_PUEL_EXTPACK_NAME))
9736 {
9737 /* Load the plugin */
9738 Utf8Str strPlugin;
9739 rc = pExtPackManager->i_getLibraryPathForExtPack(g_szVDPlugin, ORACLE_PUEL_EXTPACK_NAME, &strPlugin);
9740 if (SUCCEEDED(rc))
9741 {
9742 vrc = VDPluginLoadFromFilename(strPlugin.c_str());
9743 if (RT_FAILURE(vrc))
9744 throw setError(VBOX_E_NOT_SUPPORTED,
9745 tr("Retrieving encryption settings of the image failed because the encryption plugin could not be loaded (%s)"),
9746 i_vdError(vrc).c_str());
9747 }
9748 else
9749 throw setError(VBOX_E_NOT_SUPPORTED,
9750 tr("Encryption is not supported because the extension pack '%s' is missing the encryption plugin (old extension pack installed?)"),
9751 ORACLE_PUEL_EXTPACK_NAME);
9752 }
9753 else
9754 throw setError(VBOX_E_NOT_SUPPORTED,
9755 tr("Encryption is not supported because the extension pack '%s' is missing"),
9756 ORACLE_PUEL_EXTPACK_NAME);
9757#else
9758 throw setError(VBOX_E_NOT_SUPPORTED,
9759 tr("Encryption is not supported because extension pack support is not built in"));
9760#endif
9761
9762 if (itKeyId == pBase->m->mapProperties.end())
9763 throw setError(VBOX_E_INVALID_OBJECT_STATE,
9764 tr("Image '%s' is configured for encryption but doesn't has a key identifier set"),
9765 pBase->m->strLocationFull.c_str());
9766
9767 /* Find the proper secret key in the key store. */
9768 if (!task.m_pSecretKeyStore)
9769 throw setError(VBOX_E_INVALID_OBJECT_STATE,
9770 tr("Image '%s' is configured for encryption but there is no key store to retrieve the password from"),
9771 pBase->m->strLocationFull.c_str());
9772
9773 SecretKey *pKey = NULL;
9774 vrc = task.m_pSecretKeyStore->retainSecretKey(itKeyId->second, &pKey);
9775 if (RT_FAILURE(vrc))
9776 throw setError(VBOX_E_INVALID_OBJECT_STATE,
9777 tr("Failed to retrieve the secret key with ID \"%s\" from the store (%Rrc)"),
9778 itKeyId->second.c_str(), vrc);
9779
9780/** @todo r=bird: Someone explain why this continue to work when
9781 * CryptoSettingsRead goes out of the scope? */
9782 Medium::CryptoFilterSettings CryptoSettingsRead;
9783 i_taskEncryptSettingsSetup(&CryptoSettingsRead, NULL, itKeyStore->second.c_str(), (const char *)pKey->getKeyBuffer(),
9784 false /* fCreateKeyStore */);
9785 vrc = VDFilterAdd(hdd, "CRYPT", VD_FILTER_FLAGS_READ, CryptoSettingsRead.vdFilterIfaces);
9786 if (vrc == VERR_VD_PASSWORD_INCORRECT)
9787 {
9788 task.m_pSecretKeyStore->releaseSecretKey(itKeyId->second);
9789 throw setError(VBOX_E_PASSWORD_INCORRECT,
9790 tr("The password to decrypt the image is incorrect"));
9791 }
9792 else if (RT_FAILURE(vrc))
9793 {
9794 task.m_pSecretKeyStore->releaseSecretKey(itKeyId->second);
9795 throw setError(VBOX_E_INVALID_OBJECT_STATE,
9796 tr("Failed to load the decryption filter: %s"),
9797 i_vdError(vrc).c_str());
9798 }
9799
9800 task.m_pSecretKeyStore->releaseSecretKey(itKeyId->second);
9801 }
9802
9803 /* Open all media in the source chain. */
9804 MediumLockList::Base::const_iterator sourceListBegin =
9805 task.mpSourceMediumLockList->GetBegin();
9806 MediumLockList::Base::const_iterator sourceListEnd =
9807 task.mpSourceMediumLockList->GetEnd();
9808 for (MediumLockList::Base::const_iterator it = sourceListBegin;
9809 it != sourceListEnd;
9810 ++it)
9811 {
9812 const MediumLock &mediumLock = *it;
9813 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
9814 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
9815
9816 /* sanity check */
9817 Assert(pMedium->m->state == MediumState_LockedRead);
9818
9819 /* Open all media in read-only mode. */
9820 vrc = VDOpen(hdd,
9821 pMedium->m->strFormat.c_str(),
9822 pMedium->m->strLocationFull.c_str(),
9823 VD_OPEN_FLAGS_READONLY | m->uOpenFlagsDef,
9824 pMedium->m->vdImageIfaces);
9825 if (RT_FAILURE(vrc))
9826 throw setError(VBOX_E_FILE_ERROR,
9827 tr("Could not open the medium storage unit '%s'%s"),
9828 pMedium->m->strLocationFull.c_str(),
9829 i_vdError(vrc).c_str());
9830 }
9831
9832 Utf8Str targetFormat(task.mFormat->i_getId());
9833 Utf8Str targetLocation(task.mFilename);
9834 uint64_t capabilities = task.mFormat->i_getCapabilities();
9835
9836 Assert(m->state == MediumState_LockedRead);
9837
9838 /* unlock before the potentially lengthy operation */
9839 thisLock.release();
9840
9841 /* ensure the target directory exists */
9842 if (capabilities & MediumFormatCapabilities_File)
9843 {
9844 rc = VirtualBox::i_ensureFilePathExists(targetLocation,
9845 !(task.mVariant & MediumVariant_NoCreateDir) /* fCreate */);
9846 if (FAILED(rc))
9847 throw rc;
9848 }
9849
9850 PVDISK targetHdd;
9851 vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &targetHdd);
9852 ComAssertRCThrow(vrc, E_FAIL);
9853
9854 try
9855 {
9856 vrc = VDCopy(hdd,
9857 VD_LAST_IMAGE,
9858 targetHdd,
9859 targetFormat.c_str(),
9860 targetLocation.c_str(),
9861 false /* fMoveByRename */,
9862 0 /* cbSize */,
9863 task.mVariant & ~MediumVariant_NoCreateDir,
9864 NULL /* pDstUuid */,
9865 VD_OPEN_FLAGS_NORMAL | VD_OPEN_FLAGS_SEQUENTIAL,
9866 NULL /* pVDIfsOperation */,
9867 task.mVDImageIfaces,
9868 task.mVDOperationIfaces);
9869 if (RT_FAILURE(vrc))
9870 throw setError(VBOX_E_FILE_ERROR,
9871 tr("Could not create the exported medium '%s'%s"),
9872 targetLocation.c_str(), i_vdError(vrc).c_str());
9873 }
9874 catch (HRESULT aRC) { rc = aRC; }
9875
9876 VDDestroy(targetHdd);
9877 }
9878 catch (HRESULT aRC) { rc = aRC; }
9879
9880 VDDestroy(hdd);
9881 }
9882 catch (HRESULT aRC) { rc = aRC; }
9883
9884 /* Everything is explicitly unlocked when the task exits,
9885 * as the task destruction also destroys the source chain. */
9886
9887 /* Make sure the source chain is released early, otherwise it can
9888 * lead to deadlocks with concurrent IAppliance activities. */
9889 task.mpSourceMediumLockList->Clear();
9890
9891 return rc;
9892}
9893
9894/**
9895 * Implementation code for the "import" task.
9896 *
9897 * This only gets started from Medium::importFile() and always runs
9898 * asynchronously. It potentially touches the media registry, so we
9899 * always save the VirtualBox.xml file when we're done here.
9900 *
9901 * @param task
9902 * @return
9903 */
9904HRESULT Medium::i_taskImportHandler(Medium::ImportTask &task)
9905{
9906 /** @todo r=klaus The code below needs to be double checked with regard
9907 * to lock order violations, it probably causes lock order issues related
9908 * to the AutoCaller usage. */
9909 HRESULT rcTmp = S_OK;
9910
9911 const ComObjPtr<Medium> &pParent = task.mParent;
9912
9913 bool fCreatingTarget = false;
9914
9915 uint64_t size = 0, logicalSize = 0;
9916 MediumVariant_T variant = MediumVariant_Standard;
9917 bool fGenerateUuid = false;
9918
9919 try
9920 {
9921 if (!pParent.isNull())
9922 if (pParent->i_getDepth() >= SETTINGS_MEDIUM_DEPTH_MAX)
9923 {
9924 AutoReadLock plock(pParent COMMA_LOCKVAL_SRC_POS);
9925 throw setError(VBOX_E_INVALID_OBJECT_STATE,
9926 tr("Cannot import image for medium '%s', because it exceeds the medium tree depth limit. Please merge some images which you no longer need"),
9927 pParent->m->strLocationFull.c_str());
9928 }
9929
9930 /* Lock all in {parent,child} order. The lock is also used as a
9931 * signal from the task initiator (which releases it only after
9932 * RTThreadCreate()) that we can start the job. */
9933 AutoMultiWriteLock2 thisLock(this, pParent COMMA_LOCKVAL_SRC_POS);
9934
9935 fCreatingTarget = m->state == MediumState_Creating;
9936
9937 /* The object may request a specific UUID (through a special form of
9938 * the setLocation() argument). Otherwise we have to generate it */
9939 Guid targetId = m->id;
9940
9941 fGenerateUuid = targetId.isZero();
9942 if (fGenerateUuid)
9943 {
9944 targetId.create();
9945 /* VirtualBox::i_registerMedium() will need UUID */
9946 unconst(m->id) = targetId;
9947 }
9948
9949
9950 PVDISK hdd;
9951 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &hdd);
9952 ComAssertRCThrow(vrc, E_FAIL);
9953
9954 try
9955 {
9956 /* Open source medium. */
9957 vrc = VDOpen(hdd,
9958 task.mFormat->i_getId().c_str(),
9959 task.mFilename.c_str(),
9960 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_SEQUENTIAL | m->uOpenFlagsDef,
9961 task.mVDImageIfaces);
9962 if (RT_FAILURE(vrc))
9963 throw setError(VBOX_E_FILE_ERROR,
9964 tr("Could not open the medium storage unit '%s'%s"),
9965 task.mFilename.c_str(),
9966 i_vdError(vrc).c_str());
9967
9968 Utf8Str targetFormat(m->strFormat);
9969 Utf8Str targetLocation(m->strLocationFull);
9970 uint64_t capabilities = task.mFormat->i_getCapabilities();
9971
9972 Assert( m->state == MediumState_Creating
9973 || m->state == MediumState_LockedWrite);
9974 Assert( pParent.isNull()
9975 || pParent->m->state == MediumState_LockedRead);
9976
9977 /* unlock before the potentially lengthy operation */
9978 thisLock.release();
9979
9980 /* ensure the target directory exists */
9981 if (capabilities & MediumFormatCapabilities_File)
9982 {
9983 HRESULT rc = VirtualBox::i_ensureFilePathExists(targetLocation,
9984 !(task.mVariant & MediumVariant_NoCreateDir) /* fCreate */);
9985 if (FAILED(rc))
9986 throw rc;
9987 }
9988
9989 PVDISK targetHdd;
9990 vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &targetHdd);
9991 ComAssertRCThrow(vrc, E_FAIL);
9992
9993 try
9994 {
9995 /* Open all media in the target chain. */
9996 MediumLockList::Base::const_iterator targetListBegin =
9997 task.mpTargetMediumLockList->GetBegin();
9998 MediumLockList::Base::const_iterator targetListEnd =
9999 task.mpTargetMediumLockList->GetEnd();
10000 for (MediumLockList::Base::const_iterator it = targetListBegin;
10001 it != targetListEnd;
10002 ++it)
10003 {
10004 const MediumLock &mediumLock = *it;
10005 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
10006
10007 /* If the target medium is not created yet there's no
10008 * reason to open it. */
10009 if (pMedium == this && fCreatingTarget)
10010 continue;
10011
10012 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
10013
10014 /* sanity check */
10015 Assert( pMedium->m->state == MediumState_LockedRead
10016 || pMedium->m->state == MediumState_LockedWrite);
10017
10018 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
10019 if (pMedium->m->state != MediumState_LockedWrite)
10020 uOpenFlags = VD_OPEN_FLAGS_READONLY;
10021 if (pMedium->m->type == MediumType_Shareable)
10022 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
10023
10024 /* Open all media in appropriate mode. */
10025 vrc = VDOpen(targetHdd,
10026 pMedium->m->strFormat.c_str(),
10027 pMedium->m->strLocationFull.c_str(),
10028 uOpenFlags | m->uOpenFlagsDef,
10029 pMedium->m->vdImageIfaces);
10030 if (RT_FAILURE(vrc))
10031 throw setError(VBOX_E_FILE_ERROR,
10032 tr("Could not open the medium storage unit '%s'%s"),
10033 pMedium->m->strLocationFull.c_str(),
10034 i_vdError(vrc).c_str());
10035 }
10036
10037 vrc = VDCopy(hdd,
10038 VD_LAST_IMAGE,
10039 targetHdd,
10040 targetFormat.c_str(),
10041 (fCreatingTarget) ? targetLocation.c_str() : (char *)NULL,
10042 false /* fMoveByRename */,
10043 0 /* cbSize */,
10044 task.mVariant & ~MediumVariant_NoCreateDir,
10045 targetId.raw(),
10046 VD_OPEN_FLAGS_NORMAL,
10047 NULL /* pVDIfsOperation */,
10048 m->vdImageIfaces,
10049 task.mVDOperationIfaces);
10050 if (RT_FAILURE(vrc))
10051 throw setError(VBOX_E_FILE_ERROR,
10052 tr("Could not create the imported medium '%s'%s"),
10053 targetLocation.c_str(), i_vdError(vrc).c_str());
10054
10055 size = VDGetFileSize(targetHdd, VD_LAST_IMAGE);
10056 logicalSize = VDGetSize(targetHdd, VD_LAST_IMAGE);
10057 unsigned uImageFlags;
10058 vrc = VDGetImageFlags(targetHdd, 0, &uImageFlags);
10059 if (RT_SUCCESS(vrc))
10060 variant = (MediumVariant_T)uImageFlags;
10061 }
10062 catch (HRESULT aRC) { rcTmp = aRC; }
10063
10064 VDDestroy(targetHdd);
10065 }
10066 catch (HRESULT aRC) { rcTmp = aRC; }
10067
10068 VDDestroy(hdd);
10069 }
10070 catch (HRESULT aRC) { rcTmp = aRC; }
10071
10072 ErrorInfoKeeper eik;
10073 MultiResult mrc(rcTmp);
10074
10075 /* Only do the parent changes for newly created media. */
10076 if (SUCCEEDED(mrc) && fCreatingTarget)
10077 {
10078 /* we set m->pParent & children() */
10079 AutoWriteLock treeLock(m->pVirtualBox->i_getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
10080
10081 Assert(m->pParent.isNull());
10082
10083 if (pParent)
10084 {
10085 /* Associate the imported medium with the parent and deassociate
10086 * from VirtualBox. Depth check above. */
10087 i_setParent(pParent);
10088
10089 /* register with mVirtualBox as the last step and move to
10090 * Created state only on success (leaving an orphan file is
10091 * better than breaking media registry consistency) */
10092 eik.restore();
10093 ComObjPtr<Medium> pMedium;
10094 mrc = pParent->m->pVirtualBox->i_registerMedium(this, &pMedium,
10095 treeLock);
10096 Assert(this == pMedium);
10097 eik.fetch();
10098
10099 if (FAILED(mrc))
10100 /* break parent association on failure to register */
10101 this->i_deparent(); // removes target from parent
10102 }
10103 else
10104 {
10105 /* just register */
10106 eik.restore();
10107 ComObjPtr<Medium> pMedium;
10108 mrc = m->pVirtualBox->i_registerMedium(this, &pMedium, treeLock);
10109 Assert(this == pMedium);
10110 eik.fetch();
10111 }
10112 }
10113
10114 if (fCreatingTarget)
10115 {
10116 AutoWriteLock mLock(this COMMA_LOCKVAL_SRC_POS);
10117
10118 if (SUCCEEDED(mrc))
10119 {
10120 m->state = MediumState_Created;
10121
10122 m->size = size;
10123 m->logicalSize = logicalSize;
10124 m->variant = variant;
10125 }
10126 else
10127 {
10128 /* back to NotCreated on failure */
10129 m->state = MediumState_NotCreated;
10130
10131 /* reset UUID to prevent it from being reused next time */
10132 if (fGenerateUuid)
10133 unconst(m->id).clear();
10134 }
10135 }
10136
10137 // now, at the end of this task (always asynchronous), save the settings
10138 {
10139 // save the settings
10140 i_markRegistriesModified();
10141 /* collect multiple errors */
10142 eik.restore();
10143 m->pVirtualBox->i_saveModifiedRegistries();
10144 eik.fetch();
10145 }
10146
10147 /* Everything is explicitly unlocked when the task exits,
10148 * as the task destruction also destroys the target chain. */
10149
10150 /* Make sure the target chain is released early, otherwise it can
10151 * lead to deadlocks with concurrent IAppliance activities. */
10152 task.mpTargetMediumLockList->Clear();
10153
10154 return mrc;
10155}
10156
10157/**
10158 * Sets up the encryption settings for a filter.
10159 */
10160void Medium::i_taskEncryptSettingsSetup(CryptoFilterSettings *pSettings, const char *pszCipher,
10161 const char *pszKeyStore, const char *pszPassword,
10162 bool fCreateKeyStore)
10163{
10164 pSettings->pszCipher = pszCipher;
10165 pSettings->pszPassword = pszPassword;
10166 pSettings->pszKeyStoreLoad = pszKeyStore;
10167 pSettings->fCreateKeyStore = fCreateKeyStore;
10168 pSettings->pbDek = NULL;
10169 pSettings->cbDek = 0;
10170 pSettings->vdFilterIfaces = NULL;
10171
10172 pSettings->vdIfCfg.pfnAreKeysValid = i_vdCryptoConfigAreKeysValid;
10173 pSettings->vdIfCfg.pfnQuerySize = i_vdCryptoConfigQuerySize;
10174 pSettings->vdIfCfg.pfnQuery = i_vdCryptoConfigQuery;
10175 pSettings->vdIfCfg.pfnQueryBytes = NULL;
10176
10177 pSettings->vdIfCrypto.pfnKeyRetain = i_vdCryptoKeyRetain;
10178 pSettings->vdIfCrypto.pfnKeyRelease = i_vdCryptoKeyRelease;
10179 pSettings->vdIfCrypto.pfnKeyStorePasswordRetain = i_vdCryptoKeyStorePasswordRetain;
10180 pSettings->vdIfCrypto.pfnKeyStorePasswordRelease = i_vdCryptoKeyStorePasswordRelease;
10181 pSettings->vdIfCrypto.pfnKeyStoreSave = i_vdCryptoKeyStoreSave;
10182 pSettings->vdIfCrypto.pfnKeyStoreReturnParameters = i_vdCryptoKeyStoreReturnParameters;
10183
10184 int vrc = VDInterfaceAdd(&pSettings->vdIfCfg.Core,
10185 "Medium::vdInterfaceCfgCrypto",
10186 VDINTERFACETYPE_CONFIG, pSettings,
10187 sizeof(VDINTERFACECONFIG), &pSettings->vdFilterIfaces);
10188 AssertRC(vrc);
10189
10190 vrc = VDInterfaceAdd(&pSettings->vdIfCrypto.Core,
10191 "Medium::vdInterfaceCrypto",
10192 VDINTERFACETYPE_CRYPTO, pSettings,
10193 sizeof(VDINTERFACECRYPTO), &pSettings->vdFilterIfaces);
10194 AssertRC(vrc);
10195}
10196
10197/**
10198 * Implementation code for the "encrypt" task.
10199 *
10200 * @param task
10201 * @return
10202 */
10203HRESULT Medium::i_taskEncryptHandler(Medium::EncryptTask &task)
10204{
10205# ifndef VBOX_WITH_EXTPACK
10206 RT_NOREF(task);
10207# endif
10208 HRESULT rc = S_OK;
10209
10210 /* Lock all in {parent,child} order. The lock is also used as a
10211 * signal from the task initiator (which releases it only after
10212 * RTThreadCreate()) that we can start the job. */
10213 ComObjPtr<Medium> pBase = i_getBase();
10214 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
10215
10216 try
10217 {
10218# ifdef VBOX_WITH_EXTPACK
10219 ExtPackManager *pExtPackManager = m->pVirtualBox->i_getExtPackManager();
10220 if (pExtPackManager->i_isExtPackUsable(ORACLE_PUEL_EXTPACK_NAME))
10221 {
10222 /* Load the plugin */
10223 Utf8Str strPlugin;
10224 rc = pExtPackManager->i_getLibraryPathForExtPack(g_szVDPlugin, ORACLE_PUEL_EXTPACK_NAME, &strPlugin);
10225 if (SUCCEEDED(rc))
10226 {
10227 int vrc = VDPluginLoadFromFilename(strPlugin.c_str());
10228 if (RT_FAILURE(vrc))
10229 throw setError(VBOX_E_NOT_SUPPORTED,
10230 tr("Encrypting the image failed because the encryption plugin could not be loaded (%s)"),
10231 i_vdError(vrc).c_str());
10232 }
10233 else
10234 throw setError(VBOX_E_NOT_SUPPORTED,
10235 tr("Encryption is not supported because the extension pack '%s' is missing the encryption plugin (old extension pack installed?)"),
10236 ORACLE_PUEL_EXTPACK_NAME);
10237 }
10238 else
10239 throw setError(VBOX_E_NOT_SUPPORTED,
10240 tr("Encryption is not supported because the extension pack '%s' is missing"),
10241 ORACLE_PUEL_EXTPACK_NAME);
10242
10243 PVDISK pDisk = NULL;
10244 int vrc = VDCreate(m->vdDiskIfaces, i_convertDeviceType(), &pDisk);
10245 ComAssertRCThrow(vrc, E_FAIL);
10246
10247 Medium::CryptoFilterSettings CryptoSettingsRead;
10248 Medium::CryptoFilterSettings CryptoSettingsWrite;
10249
10250 void *pvBuf = NULL;
10251 const char *pszPasswordNew = NULL;
10252 try
10253 {
10254 /* Set up disk encryption filters. */
10255 if (task.mstrCurrentPassword.isEmpty())
10256 {
10257 /*
10258 * Query whether the medium property indicating that encryption is
10259 * configured is existing.
10260 */
10261 settings::StringsMap::iterator it = pBase->m->mapProperties.find("CRYPT/KeyStore");
10262 if (it != pBase->m->mapProperties.end())
10263 throw setError(VBOX_E_PASSWORD_INCORRECT,
10264 tr("The password given for the encrypted image is incorrect"));
10265 }
10266 else
10267 {
10268 settings::StringsMap::iterator it = pBase->m->mapProperties.find("CRYPT/KeyStore");
10269 if (it == pBase->m->mapProperties.end())
10270 throw setError(VBOX_E_INVALID_OBJECT_STATE,
10271 tr("The image is not configured for encryption"));
10272
10273 i_taskEncryptSettingsSetup(&CryptoSettingsRead, NULL, it->second.c_str(), task.mstrCurrentPassword.c_str(),
10274 false /* fCreateKeyStore */);
10275 vrc = VDFilterAdd(pDisk, "CRYPT", VD_FILTER_FLAGS_READ, CryptoSettingsRead.vdFilterIfaces);
10276 if (vrc == VERR_VD_PASSWORD_INCORRECT)
10277 throw setError(VBOX_E_PASSWORD_INCORRECT,
10278 tr("The password to decrypt the image is incorrect"));
10279 else if (RT_FAILURE(vrc))
10280 throw setError(VBOX_E_INVALID_OBJECT_STATE,
10281 tr("Failed to load the decryption filter: %s"),
10282 i_vdError(vrc).c_str());
10283 }
10284
10285 if (task.mstrCipher.isNotEmpty())
10286 {
10287 if ( task.mstrNewPassword.isEmpty()
10288 && task.mstrNewPasswordId.isEmpty()
10289 && task.mstrCurrentPassword.isNotEmpty())
10290 {
10291 /* An empty password and password ID will default to the current password. */
10292 pszPasswordNew = task.mstrCurrentPassword.c_str();
10293 }
10294 else if (task.mstrNewPassword.isEmpty())
10295 throw setError(VBOX_E_OBJECT_NOT_FOUND,
10296 tr("A password must be given for the image encryption"));
10297 else if (task.mstrNewPasswordId.isEmpty())
10298 throw setError(VBOX_E_INVALID_OBJECT_STATE,
10299 tr("A valid identifier for the password must be given"));
10300 else
10301 pszPasswordNew = task.mstrNewPassword.c_str();
10302
10303 i_taskEncryptSettingsSetup(&CryptoSettingsWrite, task.mstrCipher.c_str(), NULL,
10304 pszPasswordNew, true /* fCreateKeyStore */);
10305 vrc = VDFilterAdd(pDisk, "CRYPT", VD_FILTER_FLAGS_WRITE, CryptoSettingsWrite.vdFilterIfaces);
10306 if (RT_FAILURE(vrc))
10307 throw setError(VBOX_E_INVALID_OBJECT_STATE,
10308 tr("Failed to load the encryption filter: %s"),
10309 i_vdError(vrc).c_str());
10310 }
10311 else if (task.mstrNewPasswordId.isNotEmpty() || task.mstrNewPassword.isNotEmpty())
10312 throw setError(VBOX_E_INVALID_OBJECT_STATE,
10313 tr("The password and password identifier must be empty if the output should be unencrypted"));
10314
10315 /* Open all media in the chain. */
10316 MediumLockList::Base::const_iterator mediumListBegin =
10317 task.mpMediumLockList->GetBegin();
10318 MediumLockList::Base::const_iterator mediumListEnd =
10319 task.mpMediumLockList->GetEnd();
10320 MediumLockList::Base::const_iterator mediumListLast =
10321 mediumListEnd;
10322 --mediumListLast;
10323 for (MediumLockList::Base::const_iterator it = mediumListBegin;
10324 it != mediumListEnd;
10325 ++it)
10326 {
10327 const MediumLock &mediumLock = *it;
10328 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
10329 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
10330
10331 Assert(pMedium->m->state == MediumState_LockedWrite);
10332
10333 /* Open all media but last in read-only mode. Do not handle
10334 * shareable media, as compaction and sharing are mutually
10335 * exclusive. */
10336 vrc = VDOpen(pDisk,
10337 pMedium->m->strFormat.c_str(),
10338 pMedium->m->strLocationFull.c_str(),
10339 m->uOpenFlagsDef | (it == mediumListLast ? VD_OPEN_FLAGS_NORMAL : VD_OPEN_FLAGS_READONLY),
10340 pMedium->m->vdImageIfaces);
10341 if (RT_FAILURE(vrc))
10342 throw setError(VBOX_E_FILE_ERROR,
10343 tr("Could not open the medium storage unit '%s'%s"),
10344 pMedium->m->strLocationFull.c_str(),
10345 i_vdError(vrc).c_str());
10346 }
10347
10348 Assert(m->state == MediumState_LockedWrite);
10349
10350 Utf8Str location(m->strLocationFull);
10351
10352 /* unlock before the potentially lengthy operation */
10353 thisLock.release();
10354
10355 vrc = VDPrepareWithFilters(pDisk, task.mVDOperationIfaces);
10356 if (RT_FAILURE(vrc))
10357 throw setError(VBOX_E_FILE_ERROR,
10358 tr("Could not prepare disk images for encryption (%Rrc): %s"),
10359 vrc, i_vdError(vrc).c_str());
10360
10361 thisLock.acquire();
10362 /* If everything went well set the new key store. */
10363 settings::StringsMap::iterator it = pBase->m->mapProperties.find("CRYPT/KeyStore");
10364 if (it != pBase->m->mapProperties.end())
10365 pBase->m->mapProperties.erase(it);
10366
10367 /* Delete KeyId if encryption is removed or the password did change. */
10368 if ( task.mstrNewPasswordId.isNotEmpty()
10369 || task.mstrCipher.isEmpty())
10370 {
10371 it = pBase->m->mapProperties.find("CRYPT/KeyId");
10372 if (it != pBase->m->mapProperties.end())
10373 pBase->m->mapProperties.erase(it);
10374 }
10375
10376 if (CryptoSettingsWrite.pszKeyStore)
10377 {
10378 pBase->m->mapProperties["CRYPT/KeyStore"] = Utf8Str(CryptoSettingsWrite.pszKeyStore);
10379 if (task.mstrNewPasswordId.isNotEmpty())
10380 pBase->m->mapProperties["CRYPT/KeyId"] = task.mstrNewPasswordId;
10381 }
10382
10383 if (CryptoSettingsRead.pszCipherReturned)
10384 RTStrFree(CryptoSettingsRead.pszCipherReturned);
10385
10386 if (CryptoSettingsWrite.pszCipherReturned)
10387 RTStrFree(CryptoSettingsWrite.pszCipherReturned);
10388
10389 thisLock.release();
10390 pBase->i_markRegistriesModified();
10391 m->pVirtualBox->i_saveModifiedRegistries();
10392 }
10393 catch (HRESULT aRC) { rc = aRC; }
10394
10395 if (pvBuf)
10396 RTMemFree(pvBuf);
10397
10398 VDDestroy(pDisk);
10399# else
10400 throw setError(VBOX_E_NOT_SUPPORTED,
10401 tr("Encryption is not supported because extension pack support is not built in"));
10402# endif
10403 }
10404 catch (HRESULT aRC) { rc = aRC; }
10405
10406 /* Everything is explicitly unlocked when the task exits,
10407 * as the task destruction also destroys the media chain. */
10408
10409 return rc;
10410}
10411
10412/* 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