VirtualBox

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

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

Main: ApplianceImplExport.cpp: More hacking on OPC exporting.

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