VirtualBox

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

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

Main/MediumImpl: Don't expost stream optimized images as preferred diff images. Fixes indirect attachments of stream optimized images where a diff needs to be created to catch writes

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

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