VirtualBox

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

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

Main,VD: Compressed the Medium::i_exportFile method (VBOX_WITH_NEW_TAR_CREATOR) and hooked it up to the export progress object.

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

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