VirtualBox

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

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

Main/Medium::i_addRawToFss: Split out the opening of the medium as we can share that with i_exportFile. Fixed decrypt problem.

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