VirtualBox

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

Last change on this file since 59448 was 59277, checked in by vboxsync, 9 years ago

D'oh.

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

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