VirtualBox

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

Last change on this file since 79241 was 78762, checked in by vboxsync, 6 years ago

Main: NULL pTask after createThread() call to catch any useage after it might be deleted. Fixed one such case in SessionMachine::takeSnapshot().

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

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