VirtualBox

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

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

Storage,DrvVD,Main,VBoxManage: Rename VBOXHDD to VDISK, the VBoxHDD module is long gone:

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