VirtualBox

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

Last change on this file since 73975 was 73858, checked in by vboxsync, 7 years ago

Main: bugref:8929: Medium::setDescription has been reordered to avoid redudant lock acquire/release operations

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

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