VirtualBox

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

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

Main: bugref:9623: Implemented DVD multi attachment by ref count.

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