VirtualBox

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

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

Main: doxygen fixes

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