VirtualBox

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

最後變更 在這個檔案從79479是 79479,由 vboxsync 提交於 6 年 前

Main: bugref:9447: VBoxSVC crashes during resizing a "normal" virtual hard disk image if the vm is runnig

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

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