VirtualBox

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

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

Main/Medium::i_addRawToFss: Removed unnecessary lock list Clear call, the destructor does the same thing and also preserve error info.

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

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