VirtualBox

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

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

Main: More hacking on OPC exporting.

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