VirtualBox

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

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

Main/MediumImpl: bugref:8344: enforce an absolute path when changing the medium location

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