VirtualBox

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

Last change on this file since 86455 was 86295, checked in by vboxsync, 5 years ago

Main/MediumImpl.cpp: indentation fixes

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

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