internal static PrivateHeader GetPrivateHeader(VirtualDisk disk) { if (disk.IsPartitioned) { long headerPos = 0; PartitionTable pt = disk.Partitions; if (pt is BiosPartitionTable) { headerPos = 0xc00; } else { foreach (var part in pt.Partitions) { if (part.GuidType == GuidPartitionTypes.WindowsLdmMetadata) { headerPos = part.LastSector * Sizes.Sector; } } } if (headerPos != 0) { disk.Content.Position = headerPos; byte[] buffer = new byte[Sizes.Sector]; disk.Content.Read(buffer, 0, buffer.Length); PrivateHeader hdr = new PrivateHeader(); hdr.ReadFrom(buffer, 0); return hdr; } } return null; }
public VirtualDiskPSDriveInfo(PSDriveInfo toCopy, string root, VirtualDisk disk) : base(toCopy.Name, toCopy.Provider, root, toCopy.Description, toCopy.Credential) { _disk = disk; _volMgr = new VolumeManager(_disk); _fsCache = new Dictionary<string, DiscFileSystem>(); }
public virtual void SetUp() { Directory.CreateDirectory(DiskFileBaseName); var clientDiskName = Path.Combine(DiskFileBaseName, Count + ".client.panda"); var otherClientDiskName = Path.Combine(DiskFileBaseName, Count + ".client2.panda"); var serverDiskName = Path.Combine(DiskFileBaseName, Count + ".server.panda"); if (File.Exists(clientDiskName)) File.Delete(clientDiskName); if (File.Exists(otherClientDiskName)) File.Delete(otherClientDiskName); if(File.Exists(serverDiskName)) File.Delete(serverDiskName); Client = VirtualDisk.CreateNew(clientDiskName,Capacity); OtherClient = VirtualDisk.CreateNew(otherClientDiskName, Capacity); Server = VirtualDisk.CreateNew(serverDiskName, Capacity); SyncClient = (ISynchronizingDisk) Client; SyncServer = (ISynchronizingDisk) Server; SyncOtherClient = (ISynchronizingDisk) OtherClient; SyncClient.ServerAssociation = serverDiskName; SyncOtherClient.ServerAssociation = serverDiskName; DiskNames = new List<string> {clientDiskName, otherClientDiskName,serverDiskName}; _managedDisks = new List<VirtualDisk> {Client,OtherClient,Server}; Count++; }
public virtual void TearDown() { if (Disk != null) { Disk.Dispose(); } if (_managedDisk != null && _managedDisk != Disk) { _managedDisk.Dispose(); } Disk = null; _managedDisk = null; try { if (File.Exists(DiskFileName)) { File.Delete(DiskFileName); } } catch (Exception e) { Console.WriteLine(e); } }
internal DynamicDiskGroup(VirtualDisk disk) { _disks = new Dictionary<Guid, DynamicDisk>(); DynamicDisk dynDisk = new DynamicDisk(disk); _database = dynDisk.Database; _disks.Add(dynDisk.Id, dynDisk); _record = dynDisk.Database.GetDiskGroup(dynDisk.GroupId); }
public override PartitionTable DetectPartitionTable(VirtualDisk disk) { if (!DetectIsPartitioned(disk.Content)) { return null; } return new PartitionMap(disk.Content); }
public virtual void SetUp() { Directory.CreateDirectory(DiskFileBaseName); DiskFileName = Path.Combine(DiskFileBaseName, Count + ".panda"); if (File.Exists(DiskFileName)) File.Delete(DiskFileName); Count++; Disk = _managedDisk = VirtualDisk.CreateNew(DiskFileName,Capacity); }
internal DynamicDisk(VirtualDisk disk) { _disk = disk; _header = GetPrivateHeader(_disk); TocBlock toc = GetTableOfContents(); long dbStart = (_header.ConfigurationStartLba * 512) + (toc.Item1Start * 512); _disk.Content.Position = dbStart; _database = new Database(_disk.Content); }
/// <summary> /// Adds a new disk to be managed. /// </summary> /// <param name="disk">The disk to manage</param> public void Add(VirtualDisk disk) { PrivateHeader header = DynamicDisk.GetPrivateHeader(disk); DynamicDiskGroup group; if (_groups.TryGetValue(header.DiskGroupId, out group)) { group.Add(disk); } else { group = new DynamicDiskGroup(disk); _groups.Add(header.DiskGroupId, group); } }
/// <summary> /// Determines if a disk is 'dynamic' (i.e. contains LDM volumes). /// </summary> /// <param name="disk">The disk to inspect</param> /// <returns><c>true</c> if the disk contains LDM volumes, else <c>false</c>.</returns> public static bool IsDynamicDisk(VirtualDisk disk) { if (disk.IsPartitioned) { foreach (var partition in disk.Partitions.Partitions) { if (IsLdmPartition(partition)) { return true; } } } return false; }
public async Task VirtualDiskExpand_Async() { string vhdxpath = Path.Combine(Environment.CurrentDirectory, "testvhdx.vhdx"); if (File.Exists(vhdxpath)) { File.Delete(vhdxpath); } using (VirtualDisk vdisk = VirtualDisk.Create(vhdxpath, VirtualDiskType.VHDX, 4 * 1024 * 1024, VirtualDiskCreateFlags.FullPhysicalAllocation)) { Assert.IsNotNull(vdisk); Assert.AreEqual((ulong)(4 * 1024 * 1024), vdisk.VirtualSize); await vdisk.ExpandAsync(new VirtualDiskExpandParameters(8 * 1024 * 1024, VirtualDiskExpandFlags.None), CancellationToken.None, null); Assert.AreEqual((ulong)(8 * 1024 * 1024), vdisk.VirtualSize); } }
public override PartitionTable DetectPartitionTable(VirtualDisk disk) { if (BiosPartitionTable.IsValid(disk.Content)) { BiosPartitionTable table = new BiosPartitionTable(disk); if (table.Count == 1 && table[0].BiosType == BiosPartitionTypes.GptProtective) { return new GuidPartitionTable(disk); } else { return table; } } else { return null; } }
protected override void DoRun() { VolumeManager volMgr = new VolumeManager(); foreach (string disk in _diskFiles.Values) { volMgr.AddDisk(VirtualDisk.OpenDisk(disk, _diskType.IsPresent ? _diskType.Value : null, FileAccess.Read, UserName, Password)); } VolumeInfo volInfo = null; if (!string.IsNullOrEmpty(VolumeId)) { volInfo = volMgr.GetVolume(VolumeId); } else if (Partition >= 0) { volInfo = volMgr.GetPhysicalVolumes()[Partition]; } else { volInfo = volMgr.GetLogicalVolumes()[0]; } DiscUtils.FileSystemInfo fsInfo = FileSystemManager.DetectFileSystems(volInfo)[0]; using (DiscFileSystem fs = fsInfo.Open(volInfo, FileSystemParameters)) { using (Stream source = fs.OpenFile(_inFilePath.Value, FileMode.Open, FileAccess.Read)) { using (FileStream outFile = new FileStream(_outFilePath.Value, FileMode.Create, FileAccess.ReadWrite)) { PumpStreams(source, outFile); } if (_hexDump.IsPresent) { source.Position = 0; HexDump.Generate(source, Console.Out); } } } }
/// <summary> /// Creates local VHD files, using the parameters specified. /// </summary> /// <param name="isDynamic">True to create a dynamic VHD, False to create a fixed VHD.</param> /// <param name="diskSizeInGb">Size of the VHD in gigabytes.</param> /// <param name="filePath">Path of the VHD file.</param> /// <param name="diskName">Name of the volume of the VHD.</param> public static void CreateVhdDisk(bool isDynamic, int diskSizeInGb, string filePath, string diskName) { var diskSize = (long)ByteSize.FromGigaBytes(diskSizeInGb).Bytes; using (var fs = new FileStream(filePath, FileMode.OpenOrCreate)) { using (VirtualDisk destDisk = isDynamic ? Disk.InitializeDynamic(fs, Ownership.None, diskSize) : Disk.InitializeFixed(fs, Ownership.None, diskSize)) { BiosPartitionTable.Initialize(destDisk, WellKnownPartitionType.WindowsNtfs); var volumeManager = new VolumeManager(destDisk); using (var destNtfs = NtfsFileSystem.Format(volumeManager.GetLogicalVolumes().FirstOrDefault(), diskName, new NtfsFormatOptions())) { destNtfs.NtfsOptions.ShortNameCreation = ShortFileNameOption.Disabled; } } fs.Flush(); // commit everything to the stream before closing } }
/// <summary> /// Initializes a new instance of the BiosPartitionedDiskBuilder class by /// cloning the partition structure of a source disk. /// </summary> /// <param name="sourceDisk">The disk to clone</param> public BiosPartitionedDiskBuilder(VirtualDisk sourceDisk) { _capacity = sourceDisk.Capacity; _biosGeometry = sourceDisk.BiosGeometry; _bootSectors = new SparseMemoryStream(); _bootSectors.SetLength(_capacity); foreach (var extent in new BiosPartitionTable(sourceDisk).GetMetadataDiskExtents()) { sourceDisk.Content.Position = extent.Start; byte[] buffer = Utilities.ReadFully(sourceDisk.Content, (int)extent.Length); _bootSectors.Position = extent.Start; _bootSectors.Write(buffer, 0, buffer.Length); } _partitionTable = new BiosPartitionTable(_bootSectors, _biosGeometry); _partitionContents = new Dictionary <int, BuilderExtent>(); }
// Extension method to handle partition formatting private static DiscFileSystem FormatPartition(this VirtualDisk Disk, int PartitionIndex) { var type = GetPartitionType(Disk.Partitions[PartitionIndex]); switch (type) { case WellKnownPartitionType.WindowsFat: return(FatFileSystem.FormatPartition(Disk, PartitionIndex, null)); case WellKnownPartitionType.WindowsNtfs: return(NtfsFileSystem.Format(Disk.Partitions[PartitionIndex].Open(), null, Disk.Geometry, Disk.Partitions[PartitionIndex].FirstSector, Disk.Partitions[PartitionIndex].SectorCount)); case WellKnownPartitionType.Linux: // return ExtFileSystem.Format(...); default: return(null); } }
public async Task ConvertVhdToImg(string vhdPath, Stream imgStream) { DiscUtils.Containers.SetupHelper.SetupContainers(); DiscUtils.FileSystems.SetupHelper.SetupFileSystems(); using var vhdDisk = VirtualDisk.OpenDisk(vhdPath, FileAccess.Read); vhdDisk.Content.Position = 0; var buffer = new byte[bufferSize]; int bytesRead; do { bytesRead = await vhdDisk.Content.ReadAsync(buffer, 0, bufferSize); await imgStream.WriteAsync(buffer, 0, bytesRead); OnDataTransferred(bytesRead); } while (bytesRead == buffer.Length); }
public void MergeTest() { const int sz = 0x03010400; try { using (var vhdp = VirtualDisk.Create(tmpfn, sz)) Assert.That(System.IO.File.Exists(tmpfn)); using (var vhd = VirtualDisk.CreateDifferencing(tmpcfn, tmpfn)) { Assert.That(System.IO.File.Exists(tmpcfn)); vhd.Merge(1, 2); } } finally { System.IO.File.Delete(tmpcfn); System.IO.File.Delete(tmpfn); } }
public SpacesVolume MakeVolume(VirtualDisk d) { SpacesVolume spacesVolume = new SpacesVolume(d.ObjectId, this); spacesVolume.Name = d.FriendlyName; spacesVolume.StripeSize = d.Interleave; spacesVolume.RaidLevel = SpacesUtil.DetermineVirtualDiskRaidLevel(d); spacesVolume.Progress = 0f; spacesVolume.Status = SpacesUtil.ToStorApiVolumeStatus(d); spacesVolume.IsSystem = false; spacesVolume.Health = d.HealthStatus; spacesVolume.OperationalStatuses = d.OperationalStatus; List <Drive> drives = new List <Drive>(); StorApiStatus volumeDrives = this.GetVolumeDrives(spacesVolume, ref drives); if (volumeDrives == StorApiStatusEnum.STOR_NO_ERROR) { spacesVolume.Drives = drives; } return(spacesVolume); }
private static void LoadStaticFiles(string rootdDir, string dir, VirtualDisk disk) { foreach (var path in Directory.GetFiles(dir)) { if (path.EndsWith(".ico")) { continue; } string folder = ""; if (rootdDir != dir) { folder = Path.GetDirectoryName(path).Substring(rootdDir.Length + 1).Replace("\\", "/"); } disk.WriteText(folder, Path.GetFileName(path), File.ReadAllText(path)); } foreach (var path in Directory.GetDirectories(dir)) { LoadStaticFiles(rootdDir, path, disk); } }
//[Test()] public void DetachTest() { const int sz = 0x03010400; try { using (var vhd = VirtualDisk.Create(tmpfn, sz)) { Assert.That(vhd.Attached, Is.False); vhd.Attach(false, false); Assert.That(vhd.Attached, Is.False); } Assert.That(VirtualDisk.GetAllAttachedVirtualDiskPaths(), Has.Some.EqualTo(tmpfn)); Assert.That(() => VirtualDisk.Detach(tmpfn), Throws.Nothing); Assert.That(VirtualDisk.GetAllAttachedVirtualDiskPaths(), Is.Empty); } finally { System.IO.File.Delete(tmpfn); } }
private void EnumerateDisk(VirtualDisk vd, string path, bool recurse, bool namesOnly) { if (!path.TrimEnd('\\').EndsWith("!")) { path += "!"; } VolumeManager volMgr = DriveInfo != null ? DriveInfo.VolumeManager : new VolumeManager(vd); LogicalVolumeInfo[] volumes = volMgr.GetLogicalVolumes(); for (int i = 0; i < volumes.Length; ++i) { string name = "Volume" + i; string volPath = MakePath(path, name);// new PathInfo(PathInfo.Parse(path, true).MountParts, "" + i).ToString(); WriteItemObject(namesOnly ? name : (object)volumes[i], volPath, true); if (recurse) { GetChildren(volPath, recurse, namesOnly); } } }
public void OpenAttachRawTest() { try { var param = new OPEN_VIRTUAL_DISK_PARAMETERS(false); using (var vhd = VirtualDisk.Open(fn, OPEN_VIRTUAL_DISK_FLAG.OPEN_VIRTUAL_DISK_FLAG_NONE, param, VIRTUAL_DISK_ACCESS_MASK.VIRTUAL_DISK_ACCESS_NONE)) { Assert.That(vhd.Attached, Is.False); var flags = ATTACH_VIRTUAL_DISK_FLAG.ATTACH_VIRTUAL_DISK_FLAG_READ_ONLY; var aparam = ATTACH_VIRTUAL_DISK_PARAMETERS.Default; var sd = ConvertStringSecurityDescriptorToSecurityDescriptor("O:BAG:BAD:(A;;GA;;;WD)"); vhd.Attach(flags, ref aparam, sd); Assert.That(vhd.Attached, Is.True); vhd.Detach(); Assert.That(vhd.Attached, Is.False); } } finally { } }
public void TryReadingFromNonExistingBlocksOnDisk() { VirtualDisk virtualDisk = VirtualDiskTestFactory.ConstructDefaultTestDisk(); ExceptionAssert.MakeSureExceptionIsRaisedBy <ArgumentOutOfRangeException>( delegate() { virtualDisk.ReadAllBytesFromBlock(int.MaxValue); }); ExceptionAssert.MakeSureExceptionIsRaisedBy <ArgumentOutOfRangeException>( delegate() { virtualDisk.ReadAllBytesFromBlock(virtualDisk.NumberOfBlocks); }); ExceptionAssert.MakeSureExceptionIsRaisedBy <ArgumentOutOfRangeException>( delegate() { virtualDisk.ReadAllBytesFromBlock(-3); }); }
public async Task CreateFromSourceTest1() { VirtualDisk h = null; try { var cts = new CancellationTokenSource(); var rpt = new Reporter(); var lastVal = 0; rpt.NewVal += (o, e) => TestContext.WriteLine($"{DateTime.Now:o} NewVal={lastVal = e}"); h = await VirtualDisk.CreateFromSource(tmpfn, fn, cts.Token, rpt); Assert.That(lastVal, Is.EqualTo(100)); Assert.That(System.IO.File.Exists(tmpfn)); TestContext.WriteLine($"New file sz: {new System.IO.FileInfo(tmpfn).Length}"); } finally { h?.Close(); System.IO.File.Delete(tmpfn); } }
public void GetSetMetadataTest() { const int sz = 0x03010200; var lfn = tmpfn + "x"; try { using (var vhd = VirtualDisk.Create(lfn, sz)) { var count = 0; Assert.That(() => count = vhd.Metadata.Count, Throws.Nothing); // Try get and set var guid = Guid.NewGuid(); Assert.That(() => vhd.Metadata.Add(guid, new SafeCoTaskMemHandle("Testing")), Throws.Nothing); Assert.That(vhd.Metadata.Count, Is.EqualTo(count + 1)); Assert.That(vhd.Metadata.ContainsKey(Guid.NewGuid()), Is.False); Assert.That(vhd.Metadata.TryGetValue(guid, out var mem), Is.True); Assert.That(mem.ToString(-1), Is.EqualTo("Testing")); // Try enumerate and get foreach (var mkv in vhd.Metadata) { Assert.That(mkv.Key, Is.Not.EqualTo(Guid.Empty)); Assert.That(mkv.Value.Size, Is.Not.Zero); TestContext.WriteLine($"{mkv.Key}={mkv.Value.Size}b:{mkv.Value.ToString(-1)}"); } // Try remove Assert.That(vhd.Metadata.Remove(guid), Is.True); Assert.That(vhd.Metadata.TryGetValue(guid, out mem), Is.False); Assert.That(vhd.Metadata.Count, Is.EqualTo(count)); } } finally { System.IO.File.Delete(lfn); } }
protected override void DoRun() { VolumeManager volMgr = new VolumeManager(); foreach (string disk in _diskFiles.Values) { volMgr.AddDisk(VirtualDisk.OpenDisk(disk, FileAccess.Read, UserName, Password)); } Stream partitionStream = null; if (!string.IsNullOrEmpty(VolumeId)) { partitionStream = volMgr.GetVolume(VolumeId).Open(); } else if (Partition >= 0) { partitionStream = volMgr.GetPhysicalVolumes()[Partition].Open(); } else { partitionStream = volMgr.GetLogicalVolumes()[0].Open(); } SparseStream cacheStream = SparseStream.FromStream(partitionStream, Ownership.None); cacheStream = new BlockCacheStream(cacheStream, Ownership.None); NtfsFileSystem fs = new NtfsFileSystem(cacheStream); fs.NtfsOptions.HideHiddenFiles = !_showHidden.IsPresent; fs.NtfsOptions.HideSystemFiles = !_showSystem.IsPresent; fs.NtfsOptions.HideMetafiles = !_showMeta.IsPresent; fs.Dump(Console.Out, ""); }
public void OpenAttachTest() { try { using (var vhd = VirtualDisk.Open(fn)) { Assert.That(vhd.Attached, Is.False); vhd.Attach(true, true, false, GetWorldFullFileSecurity()); Assert.That(vhd.Attached, Is.True); TestContext.WriteLine(vhd.PhysicalPath); Assert.That(vhd.PhysicalPath, Is.Not.Null); // must be attached vhd.Detach(); Assert.That(vhd.Attached, Is.False); vhd.Attach(); Assert.That(vhd.Attached, Is.True); vhd.Close(); Assert.That(vhd.Attached, Is.False); } } finally { } }
public static VirtualFileSystem CreateFileSystemFromExistingStream(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } VirtualDisk disk = VirtualDisk.CreateFromStream(stream); var diskStructuresManager = new FileSystemNodeStorage(disk); FileSystemHeader header = diskStructuresManager.ReadFileSystemHeader(VirtualDiskFormatter.FileSystemHeaderBlockIndex); var nameValidator = FileSystemArtifactNamesValidator.Default; var pathValidator = PathValidator.Default; var pathBuilder = PathBuilder.Default; var nodeResolver = new NodeResolver(disk, diskStructuresManager, StringComparer.OrdinalIgnoreCase, header.RootBlockOffset, VirtualFileSystem.Root, VirtualFileSystem.DirectorySeparatorChar, pathValidator, pathBuilder); return(VirtualFileSystem.CreateFromDisk(disk, StringComparer.OrdinalIgnoreCase, nodeResolver, pathBuilder, nameValidator, pathValidator)); }
private async Task BackupVirtualDisk(VirtualDisk vd, IBackupLocationFactoryResolver locationFactoryResolver) { IBackupLocationFactory targetFactory = locationFactoryResolver.Resolve(LocationType); IBackupLocationFactory sourceFactory = locationFactoryResolver.Resolve(VirtualMachine.SourceLocationType); string backupLocation = $"{Path}/{vd.FileName}"; Stream targetStream = targetFactory.Open(backupLocation); Stream sourceStream = sourceFactory.Open(vd); byte[] buffer = new byte[512]; while (sourceStream.Position < sourceStream.Length) { long remainingBytes = sourceStream.Length - sourceStream.Position; if (remainingBytes < buffer.Length) { buffer = new byte[remainingBytes]; } await sourceStream.ReadAsync(buffer); await targetStream.WriteAsync(buffer); } targetStream.Close(); sourceStream.Close(); _virtualDiskBackupLocations.Add(vd.FileName, backupLocation); }
public void OpenAttachRawTest() { try { var param = new OPEN_VIRTUAL_DISK_PARAMETERS(false); using (var vhd = VirtualDisk.Open(fn, OPEN_VIRTUAL_DISK_FLAG.OPEN_VIRTUAL_DISK_FLAG_NONE, param, VIRTUAL_DISK_ACCESS_MASK.VIRTUAL_DISK_ACCESS_NONE)) { Assert.That(vhd.Attached, Is.False); var flags = ATTACH_VIRTUAL_DISK_FLAG.ATTACH_VIRTUAL_DISK_FLAG_READ_ONLY; var aparam = ATTACH_VIRTUAL_DISK_PARAMETERS.Default; if (!ConvertStringSecurityDescriptorToSecurityDescriptor("O:BAG:BAD:(A;;GA;;;WD)", SDDL_REVISION.SDDL_REVISION_1, out SafeHGlobalHandle sd, out uint hLen)) { Win32Error.ThrowLastError(); } vhd.Attach(flags, ref aparam, (IntPtr)sd); Assert.That(vhd.Attached, Is.True); vhd.Detach(); Assert.That(vhd.Attached, Is.False); } } finally { } }
// Note: этот код специально прилеплен к и без того немаленькому VirtualFileSystem. Это повышает discoverability фабричных методов (по сравнению с выделением фабрики) и усиливает ограничения (private-конструктор против internal-конструктора). /// <summary> /// Создает виртуальную файловую систему с настройками по умолчанию, на основе указанного файла. /// </summary> /// <param name="fullPathForFile"></param> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="FileSystemCreationFailedException"></exception> public static VirtualFileSystem OpenExisting(string fullPathForFile) { if (String.IsNullOrEmpty(fullPathForFile)) { throw new ArgumentNullException("fullPathForFile"); } FileStream stream = CreateStreamFromExistingFileWrappingExceptions(fullPathForFile); try { VirtualDisk disk = VirtualDisk.CreateFromStream(stream); var diskStructuresManager = new FileSystemNodeStorage(disk); FileSystemHeader header = diskStructuresManager.ReadFileSystemHeader(VirtualDiskFormatter.FileSystemHeaderBlockIndex); var nameValidator = FileSystemArtifactNamesValidator.Default; var pathValidator = PathValidator.Default; var pathBuilder = PathBuilder.Default; var nodeResolver = new NodeResolver(disk, diskStructuresManager, StringComparer.OrdinalIgnoreCase, header.RootBlockOffset, VirtualFileSystem.Root, VirtualFileSystem.DirectorySeparatorChar, pathValidator, pathBuilder); return(VirtualFileSystem.CreateFromDisk(disk, StringComparer.OrdinalIgnoreCase, nodeResolver, pathBuilder, nameValidator, pathValidator)); } catch (VirtualDiskCreationFailedException exception) { throw CreateGenericSystemCreationFromExistingFileException(exception, fullPathForFile); } catch (InconsistentDataDetectedException exception) { throw CreateGenericSystemCreationFromExistingFileException(exception, fullPathForFile); } }
public VirtualDisk[] QuerySnapshotVirtualDisks(string snapshot) { ManagedObjectReference morSnapshot = new ManagedObjectReference { @type = "VirtualMachineSnapshot", Value = snapshot }; VirtualMachineConfigInfo vmci = (VirtualMachineConfigInfo)_pc.Get(morSnapshot, "config"); var devices = vmci?.hardware?.device; List <VirtualDisk> virtualDisks = new List <VirtualDisk>(); if (null != devices) { foreach (var device in devices) { VirtualDisk vdisk = (device as VirtualDisk); if (null != vdisk) { virtualDisks.Add(vdisk); } } } return(virtualDisks.ToArray()); }
public void TryWritingToNonExistingBlocksOnDisk() { VirtualDisk virtualDisk = VirtualDiskTestFactory.ConstructDefaultTestDisk(); byte[] bytesToWrite = new byte[100]; ExceptionAssert.MakeSureExceptionIsRaisedBy <ArgumentOutOfRangeException>( delegate() { virtualDisk.WriteBytesToBlock(-2, bytesToWrite); }); ExceptionAssert.MakeSureExceptionIsRaisedBy <ArgumentOutOfRangeException>( delegate() { virtualDisk.WriteBytesToBlock(virtualDisk.NumberOfBlocks, bytesToWrite); }); ExceptionAssert.MakeSureExceptionIsRaisedBy <ArgumentOutOfRangeException>( delegate() { virtualDisk.WriteBytesToBlock(int.MaxValue, bytesToWrite); }); }
protected override void DoRun() { using (VirtualDisk inDisk = VirtualDisk.OpenDisk(_inFile.Value, FileAccess.Read, UserName, Password)) { VirtualDiskParameters diskParams = inDisk.Parameters; diskParams.AdapterType = AdapterType; VirtualDiskTypeInfo diskTypeInfo = VirtualDisk.GetDiskType(OutputDiskType, OutputDiskVariant); if (diskTypeInfo.DeterministicGeometry) { diskParams.Geometry = diskTypeInfo.CalcGeometry(diskParams.Capacity); } if (_translation.IsPresent && _translation.EnumValue != GeometryTranslation.None) { diskParams.BiosGeometry = diskParams.Geometry.TranslateToBios(diskParams.Capacity, _translation.EnumValue); } else if (!inDisk.DiskTypeInfo.PreservesBiosGeometry) { // In case the BIOS geometry was just a default, it's better to override based on the physical geometry // of the new disk. diskParams.BiosGeometry = Geometry.MakeBiosSafe(diskParams.Geometry, diskParams.Capacity); } using (VirtualDisk outDisk = VirtualDisk.CreateDisk(OutputDiskType, OutputDiskVariant, _outFile.Value, diskParams, UserName, Password)) { if (outDisk.Capacity < inDisk.Capacity) { Console.WriteLine("ERROR: The output disk is smaller than the input disk, conversion aborted"); } SparseStream contentStream = inDisk.Content; if (_translation.IsPresent && _translation.EnumValue != GeometryTranslation.None) { SnapshotStream ssStream = new SnapshotStream(contentStream, Ownership.None); ssStream.Snapshot(); UpdateBiosGeometry(ssStream, inDisk.BiosGeometry, diskParams.BiosGeometry); contentStream = ssStream; } StreamPump pump = new StreamPump() { InputStream = contentStream, OutputStream = outDisk.Content, SparseCopy = !_wipe.IsPresent }; if (!Quiet) { long totalBytes = contentStream.Length; if (!_wipe.IsPresent) { totalBytes = 0; foreach (var se in contentStream.Extents) { totalBytes += se.Length; } } DateTime now = DateTime.Now; pump.ProgressEvent += (o, e) => { ShowProgress("Progress", totalBytes, now, o, e); }; } pump.Run(); } } }
protected void SyncTo(VirtualDisk source, VirtualDisk destination, DateTime since) { Assert.That(source, Is.InstanceOf<ISynchronizingDisk>(), "source"); Assert.That(destination, Is.InstanceOf<ISynchronizingDisk>(), "destination"); var syncSource = (ISynchronizingDisk)source; var syncDestination = (ISynchronizingDisk)destination; Assert.That(syncSource.BlockSize, Is.EqualTo(syncDestination.BlockSize), "block sizes source should match destination"); var buffer = new byte[syncSource.BlockSize]; foreach (var offset in syncSource.GetJournalEntriesSince(since).Select(x => x.BlockOffset)) { syncSource.DirectRead(offset, buffer, 0); syncDestination.ReceiveChanges(offset, buffer); } syncSource.NotifySynchronized(); }
/// <summary> /// Creates a new partition table on a disk. /// </summary> /// <param name="disk">The disk to initialize.</param> /// <returns>An object to access the newly created partition table</returns> public static BiosPartitionTable Initialize(VirtualDisk disk) { return Initialize(disk.Content, disk.BiosGeometry); }
public VirtualDeviceConfigSpec createVirtualDisk(String volName, int diskCtlrKey, ManagedObjectReference datastoreRef, int diskSizeMB) { String volumeName = getVolumeName(volName); VirtualDeviceConfigSpec diskSpec = new VirtualDeviceConfigSpec(); diskSpec.fileOperation = VirtualDeviceConfigSpecFileOperation.create; diskSpec.fileOperationSpecified = true; diskSpec.operation = VirtualDeviceConfigSpecOperation.add; diskSpec.operationSpecified = true; VirtualDisk disk = new VirtualDisk(); VirtualDiskFlatVer2BackingInfo diskfileBacking = new VirtualDiskFlatVer2BackingInfo(); diskfileBacking.fileName = volumeName; diskfileBacking.diskMode = "persistent"; disk.key = 0; disk.controllerKey = diskCtlrKey; disk.unitNumber = 0; disk.backing = diskfileBacking; disk.capacityInKB = diskSizeMB; disk.controllerKeySpecified = true; disk.unitNumberSpecified = true; diskSpec.device = disk; return diskSpec; }
private void CreateDiffDisk() { string child; PSObject parentObj = ResolveNewDiskPath(out child); PSObject baseDiskObj = SessionState.InvokeProvider.Item.Get(new string[] { BaseDisk }, false, true)[0]; VirtualDisk baseDisk = null; try { if (baseDiskObj.BaseObject is FileInfo) { baseDisk = VirtualDisk.OpenDisk(((FileInfo)baseDiskObj.BaseObject).FullName, FileAccess.Read); } else if (baseDiskObj.BaseObject is DiscFileInfo) { DiscFileInfo dfi = (DiscFileInfo)baseDiskObj.BaseObject; baseDisk = VirtualDisk.OpenDisk(dfi.FileSystem, dfi.FullName, FileAccess.Read); } else { WriteError(new ErrorRecord( new FileNotFoundException("The file specified by the BaseDisk parameter doesn't exist"), "BadBaseDiskLocation", ErrorCategory.InvalidArgument, null)); return; } VirtualDisk newDisk = null; if (parentObj.BaseObject is DirectoryInfo) { string path = Path.Combine(((DirectoryInfo)parentObj.BaseObject).FullName, child); using (baseDisk.CreateDifferencingDisk(path)) { } newDisk = new OnDemandVirtualDisk(path, FileAccess.ReadWrite); } else if (parentObj.BaseObject is DiscDirectoryInfo) { DiscDirectoryInfo ddi = (DiscDirectoryInfo)parentObj.BaseObject; string path = Path.Combine(ddi.FullName, child); using (baseDisk.CreateDifferencingDisk(ddi.FileSystem, path)) { } newDisk = new OnDemandVirtualDisk(ddi.FileSystem, path, FileAccess.ReadWrite); } else { WriteError(new ErrorRecord( new DirectoryNotFoundException("Cannot create a virtual disk in that location"), "BadDiskLocation", ErrorCategory.InvalidArgument, null)); return; } WriteObject(newDisk, false); } finally { if (baseDisk != null) { baseDisk.Dispose(); } } }
/// <summary> /// Formats a virtual hard disk partition. /// </summary> /// <param name="disk">The disk containing the partition</param> /// <param name="partitionIndex">The index of the partition on the disk</param> /// <param name="label">The volume label for the partition (or null)</param> /// <returns>An object that provides access to the newly created partition file system</returns> public static FatFileSystem FormatPartition(VirtualDisk disk, int partitionIndex, string label) { using (Stream partitionStream = disk.Partitions[partitionIndex].Open()) { return FormatPartition( partitionStream, label, disk.Geometry, (int)disk.Partitions[partitionIndex].FirstSector, (int)(1 + disk.Partitions[partitionIndex].LastSector - disk.Partitions[partitionIndex].FirstSector), 0); } }
public void TemporarilyCloseDisk() { if (_disk != null) { lock (this) { if (_disk != null) { _disk.Dispose(); _disk = null; } } } }
/// <summary> /// Creates a new partition table on a disk. /// </summary> /// <param name="disk">The disk to initialize.</param> /// <returns>An object to access the newly created partition table</returns> public static GuidPartitionTable Initialize(VirtualDisk disk) { return(Initialize(disk.Content, disk.Geometry)); }
/// <summary> /// Gets all of the partition tables found on a disk. /// </summary> /// <param name="disk">The disk to inspect.</param> /// <returns>It is rare for a disk to have multiple partition tables, but theoretically /// possible.</returns> public static IList<PartitionTable> GetPartitionTables(VirtualDisk disk) { List<PartitionTable> tables = new List<PartitionTable>(); foreach (var factory in Factories) { PartitionTable table = factory.DetectPartitionTable(disk); if (table != null) { tables.Add(table); } } return tables; }
/// <summary> /// Determines if a disk is partitioned with a known partitioning scheme. /// </summary> /// <param name="disk">The disk to check.</param> /// <returns><c>true</c> if the disk is partitioned, else <c>false</c>.</returns> public static bool IsPartitioned(VirtualDisk disk) { return IsPartitioned(disk.Content); }
/// <summary> /// Initializes a new instance of the BiosPartitionTable class. /// </summary> /// <param name="disk">The disk containing the partition table</param> public BiosPartitionTable(VirtualDisk disk) { Init(disk.Content, disk.BiosGeometry); }
protected override void ProcessRecord() { PSObject diskObject = null; VirtualDisk disk = null; if (InputObject != null) { diskObject = InputObject; disk = diskObject.BaseObject as VirtualDisk; } if (disk == null && string.IsNullOrEmpty(LiteralPath)) { WriteError(new ErrorRecord( new ArgumentException("No disk specified"), "NoDiskSpecified", ErrorCategory.InvalidArgument, null)); return; } if (disk == null) { diskObject = SessionState.InvokeProvider.Item.Get(LiteralPath)[0]; VirtualDisk vdisk = diskObject.BaseObject as VirtualDisk; if (vdisk == null) { WriteError(new ErrorRecord( new ArgumentException("Path specified is not a virtual disk"), "BadDiskSpecified", ErrorCategory.InvalidArgument, null)); return; } disk = vdisk; } int newIndex; if (string.IsNullOrEmpty(Size)) { newIndex = disk.Partitions.Create(Type, Active); } else { long size; if (!DiscUtils.Common.Utilities.TryParseDiskSize(Size, out size)) { WriteError(new ErrorRecord( new ArgumentException("Unable to parse the volume size"), "BadVolumeSize", ErrorCategory.InvalidArgument, null)); return; } newIndex = disk.Partitions.Create(size, Type, Active); } long startSector = disk.Partitions[newIndex].FirstSector; VolumeManager volMgr = null; // Changed volume layout, force a rescan var drive = diskObject.Properties["PSDrive"].Value as VirtualDiskPSDriveInfo; if (drive != null) { drive.RescanVolumes(); volMgr = drive.VolumeManager; } else { volMgr = new VolumeManager(disk); } foreach (var vol in volMgr.GetLogicalVolumes()) { if (vol.PhysicalStartSector == startSector) { WriteObject(vol); } } }
public void CreateMemDisk(uint totalBlockCount = 256, int blockCapacity = 16, int dataBlockCapcity = 128) { Disk = SingleInstanceVirtualDiskImpl.Create( SingleInstanceMemBlockManager.Create(totalBlockCount, (BlockOffset) 1, blockCapacity, dataBlockCapcity), new AscendingOffsetLockingPolicy()); }
public void Add(VirtualDisk disk) { DynamicDisk dynDisk = new DynamicDisk(disk); _disks.Add(dynDisk.Id, dynDisk); }
public abstract PartitionTable DetectPartitionTable(VirtualDisk disk);
public void RegisterDisk(string fileName, VirtualDisk vdisk, [NotNull] Dispatcher dispatcher) { if (fileName == null) throw new ArgumentNullException("fileName"); if (vdisk == null) throw new ArgumentNullException("vdisk"); if (dispatcher == null) throw new ArgumentNullException("dispatcher"); var name = Path.GetFileNameWithoutExtension(fileName) ?? "disk" + Interlocked.Increment(ref _uniqueDiskNameCounter); // have the virtual disk dispatch its notifications on the UI thread. Debug.Assert(dispatcher != null); vdisk.NotificationDispatcher = new WindowsDispatcherAdapter(dispatcher); var diskModel = new DiskViewModel { Disk = vdisk, Name = name, FileName = fileName }; OpenDisks.Add(diskModel); }
private void ExecuteCut(object sender, ExecutedRoutedEventArgs e) { // copy can only happen on a virtualnode var vn = e.Parameter as VirtualNode; if (vn != null) { // buffer from which disk the node is _pasteBufferDisk = vn.Disk; // empty _pasteBufferNodes _pasteBufferNodes.Clear(); // add selected node to _pasteBufferNodes _pasteBufferNodes.Add(vn); _isCut = true; } else { throw new PandaException("No virtualnode clicked."); } }
protected override void DoRun() { VolumeManager volMgr = new VolumeManager(); foreach (string disk in _diskFiles.Values) { volMgr.AddDisk(VirtualDisk.OpenDisk(disk, FileAccess.Read, UserName, Password)); } VolumeInfo volInfo = null; if (!string.IsNullOrEmpty(VolumeId)) { volInfo = volMgr.GetVolume(VolumeId); } else if (Partition >= 0) { volInfo = volMgr.GetPhysicalVolumes()[Partition]; } else { volInfo = volMgr.GetLogicalVolumes()[0]; } using (NtfsFileSystem fs = new NtfsFileSystem(volInfo.Open())) { MasterFileTable mft = fs.GetMasterFileTable(); if (_recoverFile.IsPresent) { MasterFileTableEntry entry = mft[long.Parse(_recoverFile.Value)]; IBuffer content = GetContent(entry); if (content == null) { Console.WriteLine("Sorry, unable to recover content"); Environment.Exit(1); } string outFile = _recoverFile.Value + "__recovered.bin"; if (File.Exists(outFile)) { Console.WriteLine("Sorry, the file already exists: " + outFile); Environment.Exit(1); } using (FileStream outFileStream = new FileStream(outFile, FileMode.CreateNew, FileAccess.Write)) { Pump(content, outFileStream); } Console.WriteLine("Possible file contents saved as: " + outFile); Console.WriteLine(); Console.WriteLine("Caution! It is rare for the file contents of deleted files to be intact - most"); Console.WriteLine("likely the contents recovered are corrupt as the space has been reused."); } else { foreach (var entry in mft.GetEntries(EntryStates.NotInUse)) { // Skip entries with no attributes, they've probably never been used. We're certainly // not going to manage to recover any useful data from them. if (entry.Attributes.Count == 0) { continue; } // Skip directories - any useful files inside will be found separately if ((entry.Flags & MasterFileTableEntryFlags.IsDirectory) != 0) { continue; } long size = GetSize(entry); string path = GetPath(mft, entry); if (!_showMeta.IsPresent && path.StartsWith(@"<root>\$Extend")) { continue; } if (!_showZeroSize.IsPresent && size == 0) { continue; } Console.WriteLine("Index: {0,-4} Size: {1,-8} Path: {2}", entry.Index, Utilities.ApproximateDiskSize(size), path); } } } }
/// <summary> /// Creates a new partition table on a disk containing a single partition. /// </summary> /// <param name="disk">The disk to initialize.</param> /// <param name="type">The partition type for the single partition</param> /// <returns>An object to access the newly created partition table</returns> public static BiosPartitionTable Initialize(VirtualDisk disk, WellKnownPartitionType type) { BiosPartitionTable table = Initialize(disk.Content, disk.BiosGeometry); table.Create(type, true); return table; }
/// <summary> /// Initializes a new instance of the BiosPartitionedDiskBuilder class by /// cloning the partition structure of a source disk. /// </summary> /// <param name="sourceDisk">The disk to clone</param> public BiosPartitionedDiskBuilder(VirtualDisk sourceDisk) { _capacity = sourceDisk.Capacity; _biosGeometry = sourceDisk.BiosGeometry; _bootSectors = new SparseMemoryStream(); _bootSectors.SetLength(_capacity); foreach (var extent in new BiosPartitionTable(sourceDisk).GetMetadataDiskExtents()) { sourceDisk.Content.Position = extent.Start; byte[] buffer = Utilities.ReadFully(sourceDisk.Content, (int)extent.Length); _bootSectors.Position = extent.Start; _bootSectors.Write(buffer, 0, buffer.Length); } _partitionTable = new BiosPartitionTable(_bootSectors, _biosGeometry); _partitionContents = new Dictionary<int, BuilderExtent>(); }
private void _checkInactivity(Task previous) { _monitorCancellation.Token.ThrowIfCancellationRequested(); if (DateTime.Now - LastAccess > _inactivityThreshold) { lock (this) { if (DateTime.Now - LastAccess > _inactivityThreshold) { if (_disk != null) { Trace.TraceInformation( "The disk {0} has been inactive since {1}. Closing the disk at {2}.", DiskName, LastAccess,DateTime.Now); _disk.Dispose(); _disk = null; return; } } } } Trace.TraceInformation("Activity detected in Disk {0} at {2}. Checking back in {1}.", DiskName, _inactivityThreshold,LastAccess); _monitorInactivity(); }
public virtual void TearDown() { if (Client != null) { Client.Dispose(); } if (Server != null) { Server.Dispose(); } if (_managedDisks != null) { foreach (var managedDisk in _managedDisks) { if (managedDisk != Client && managedDisk != Server) { managedDisk.Dispose(); } } } Client = Server = null; _managedDisks = null; foreach (var diskName in DiskNames) { try { if (File.Exists(diskName)) { File.Delete(diskName); } } catch (Exception e) { Console.WriteLine(e); } } }
/// <summary> /// Initializes a new instance of the GuidPartitionTable class. /// </summary> /// <param name="disk">The disk containing the partition table</param> public GuidPartitionTable(VirtualDisk disk) { Init(disk.Content, disk.Geometry); }
protected virtual void Dispose(bool disposing) { if (disposing) { if (Disk != null) { Disk.Dispose(); Disk = null; } var disposable = Disk as IDisposable; if (disposable != null) { disposable.Dispose(); } Disk = null; } }