VirtualBox

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

最後變更 在這個檔案從63563是 63563,由 vboxsync 提交於 9 年 前

scm: cleaning up todos

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

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