Beispiel #1
0
        /// <summary>
        /// This method creates a .vhd hard drive formatted in NTFS.
        /// </summary>
        /// <param name="diskSize">The size of the disk in bytes.</param>
        /// <param name="location">Defines the physical location and file name. .vhd extension required.</param>
        /// <param name="label">The label to be given to the disk.</param>
        /// <param name="dynamic">Determines whether or not the disk will be of fixed size or dynamic size.</param>
        /// <returns>A bool determining if the method succeeded.</returns>
        public bool CreateNtfsDrive(long diskSize, string location, string label, bool dynamic)
        {
            try
            {
                using (Stream vhdStream = File.Create(@location))
                {
                    Disk disk = null;

                    if (dynamic)
                    {
                        disk = Disk.InitializeDynamic(vhdStream, Ownership.None, diskSize);
                    }
                    else
                    {
                        disk = Disk.InitializeFixed(vhdStream, Ownership.None, diskSize);
                    }

                    BiosPartitionTable.Initialize(disk, WellKnownPartitionType.WindowsNtfs);
                    NtfsFileSystem.Format(new VolumeManager(disk).GetLogicalVolumes()[0], label);

                    return(true);
                }
            }
            catch (IOException e)
            {
                Console.WriteLine(e.StackTrace);
                return(false);
            }
        }
Beispiel #2
0
        void InitializeVhdManually(DiscUtils.Vhd.Disk vhdDisk)
        {
            BiosPartitionTable.Initialize(vhdDisk, WellKnownPartitionType.WindowsNtfs);
            // GuidPartitionTable.Initialize(vhdDisk,  WellKnownPartitionType.WindowsNtfs);

            var volMgr        = new VolumeManager(vhdDisk);
            var logicalVolume = volMgr.GetLogicalVolumes()[0];

            var label = $"XVDTool conversion";

            using (var destNtfs = NtfsFileSystem.Format(logicalVolume, label, new NtfsFormatOptions()))
            {
                destNtfs.NtfsOptions.ShortNameCreation = ShortFileNameOption.Disabled;

                // NOTE: For VHD creation we just assume a single partition
                foreach (var file in IterateFilesystem(partitionNumber: 0))
                {
                    var fh = file.OpenRead();

                    if (!destNtfs.Exists(file.DirectoryName))
                    {
                        destNtfs.CreateDirectory(file.DirectoryName);
                    }

                    using (Stream dest = destNtfs.OpenFile(file.FullName, FileMode.Create,
                                                           FileAccess.ReadWrite))
                    {
                        fh.CopyTo(dest);
                        dest.Flush();
                    }

                    fh.Close();
                }
            }
        }
Beispiel #3
0
        public static DiscFileSystem FormatStream(string fileSystemName, Stream stream, long size, string label)
        {
            switch (fileSystemName)
            {
            case "NTFS":
            {
                var geometry = FindBasicGeometry(stream, size);

                Logger.Info("Formatting stream as NTFS");
                return(NtfsFileSystem.Format(stream, label, geometry, 0, geometry.TotalSectorsLong));
            }

            case "FAT":
            {
                var geometry = FindBasicGeometry(stream, size);

                Logger.Info("Formatting stream as FAT");
#pragma warning disable CS0618 // Typ oder Element ist veraltet
                return(FatFileSystem.FormatPartition(stream, label, geometry, 0, geometry.TotalSectors, 0));

#pragma warning restore CS0618 // Typ oder Element ist veraltet
            }

            default:
            {
                Logger.Error("Requested file system is not supported (Requested {0}, supported: NTFS, FAT)",
                             fileSystemName);
                Environment.Exit(1);
                break;
            }
            }

            return(null);
        }
Beispiel #4
0
        public static DiscFileSystem FormatFileSystemWithTemplate(Stream template, Stream output,
                                                                  long firstSector, long sectorCount, long availableSpace)
        {
            if (NtfsFileSystem.Detect(template))
            {
                var templateFS = new NtfsFileSystem(template);
                var newSize    = Math.Min(templateFS.Size, availableSpace);

                Logger.Verbose("Formatting stream as <NTFS> file system ({0}B, 0x{1}-0x{2})",
                               newSize, firstSector.ToString("X2"), sectorCount.ToString("X2"));

                return(NtfsFileSystem.Format(output, templateFS.VolumeLabel,
                                             Geometry.FromCapacity(newSize), firstSector, sectorCount,
                                             templateFS.ReadBootCode()));
            }

            /* else if (FatFileSystem.Detect(template))
             * {
             *  var templateFS = new FatFileSystem(template);
             *  var newSize = Math.Min(templateFS.Size, availableSpace);
             *
             *  Logger.Verbose("Formatting streams as <FAT> ({0}B, 0x{1}-0x{2})",
             *      newSize, firstSector.ToString("X2"), sectorCount.ToString("X2"));
             *
             *  return FatFileSystem.FormatPartition(output, templateFS.VolumeLabel,
             *      Geometry.FromCapacity(newSize), (int)firstSector, (int)sectorCount, 13);
             * } */

            return(null);
        }
        protected override void ProcessRecord()
        {
            PSObject   volInfoObj = null;
            VolumeInfo volInfo    = null;

            if (InputObject != null)
            {
                volInfoObj = InputObject;
                volInfo    = volInfoObj.BaseObject as VolumeInfo;
            }
            if (volInfo == null && string.IsNullOrEmpty(LiteralPath))
            {
                WriteError(new ErrorRecord(
                               new ArgumentException("No volume specified"),
                               "NoVolumeSpecified",
                               ErrorCategory.InvalidArgument,
                               null));
                return;
            }

            if (Filesystem != FileSystemType.Ntfs)
            {
                WriteError(new ErrorRecord(
                               new ArgumentException("Unknown filesystem type"),
                               "BadFilesystem",
                               ErrorCategory.InvalidArgument,
                               null));
                return;
            }

            if (volInfo == null)
            {
                volInfoObj = SessionState.InvokeProvider.Item.Get(LiteralPath)[0];
                volInfo    = volInfoObj.BaseObject as VolumeInfo;
            }

            if (volInfo == null)
            {
                WriteError(new ErrorRecord(
                               new ArgumentException("Path specified is not a disk volume"),
                               "BadVolumeSpecified",
                               ErrorCategory.InvalidArgument,
                               null));
                return;
            }

            var driveProp = volInfoObj.Properties["PSDrive"];

            if (driveProp != null)
            {
                var drive = driveProp.Value as VirtualDiskPSDriveInfo;
                if (drive != null)
                {
                    drive.UncacheFileSystem(volInfo.Identity);
                }
            }

            NtfsFileSystem.Format(volInfo, Label);
        }
Beispiel #6
0
        public void Format_LargeDisk()
        {
            long size = 1024L * 1024 * 1024L * 1024; // 1 TB
            SparseMemoryStream partStream = new SparseMemoryStream();

            NtfsFileSystem.Format(partStream, "New Partition", Geometry.FromCapacity(size), 0, size / 512);

            NtfsFileSystem ntfs = new NtfsFileSystem(partStream);

            ntfs.Dump(TextWriter.Null, "");
        }
Beispiel #7
0
        public void Format_SmallDisk()
        {
            long size = 8 * 1024 * 1024;
            SparseMemoryStream partStream = new SparseMemoryStream();

            //VirtualDisk disk = Vhd.Disk.InitializeDynamic(partStream, Ownership.Dispose, size);
            NtfsFileSystem.Format(partStream, "New Partition", Geometry.FromCapacity(size), 0, size / 512);

            NtfsFileSystem ntfs = new NtfsFileSystem(partStream);

            ntfs.Dump(TextWriter.Null, "");
        }
Beispiel #8
0
        private static void CreateVirtualDisk(string filePath, int size)
        {
            using (FileStream fsStream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                using (VirtualDisk disk = DiscUtils.Vhd.Disk.InitializeDynamic(fsStream, DiscUtils.Streams.Ownership.Dispose, size * 1024 * 1024))
                {
                    GuidPartitionTable.Initialize(disk, WellKnownPartitionType.WindowsNtfs);

                    PhysicalVolumeInfo volume = VolumeManager.GetPhysicalVolumes(disk)[0];

                    NtfsFileSystem.Format(volume, "CryptoBox");
                }
        }
 private void CreateDisk(string targetFilePath, long size, string diskLabel)
 {
     // Create the disk
     using (var vhdStream = File.Create(targetFilePath))
     {
         var disk = Disk.InitializeDynamic(vhdStream, Ownership.None, size);
         BiosPartitionTable.Initialize(disk, WellKnownPartitionType.WindowsNtfs);
         using (var fs = NtfsFileSystem.Format(new VolumeManager(disk).GetLogicalVolumes()[0], diskLabel))
         {
             //fs.CreateDirectory(@"TestDir\CHILD");
             // do other things with the file system...
         }
     }
 }
Beispiel #10
0
        /// <summary>
        /// Creates a temporary vhd of the given size in GB.
        /// The created VHD is dynamically allocated and is of type VHD (legacy)
        /// </summary>
        /// <param name="sizeInGB">The size of the VHD in GB</param>
        /// <returns>The path to the created vhd</returns>
        internal static string CreateVirtualDisk(long sizeInGB = 10)
        {
            long   diskSize = sizeInGB * 1024 * 1024 * 1024;
            string tempVhd  = Path.GetTempFileName();

            using Stream vhdStream = File.Create(tempVhd);
            using Disk disk        = Disk.InitializeDynamic(vhdStream, DiscUtils.Streams.Ownership.Dispose, diskSize);

            BiosPartitionTable table         = BiosPartitionTable.Initialize(disk, WellKnownPartitionType.WindowsNtfs);
            PartitionInfo      ntfsPartition = table.Partitions[0];

            NtfsFileSystem.Format(ntfsPartition.Open(), "Windows UUP Medium", Geometry.FromCapacity(diskSize), ntfsPartition.FirstSector, ntfsPartition.SectorCount);

            return(tempVhd);
        }
Beispiel #11
0
        public void ExtentInfo()
        {
            using (SparseMemoryStream ms = new SparseMemoryStream())
            {
                Geometry       diskGeometry = Geometry.FromCapacity(30 * 1024 * 1024);
                NtfsFileSystem ntfs         = NtfsFileSystem.Format(ms, "", diskGeometry, 0, diskGeometry.TotalSectorsLong);

                // Check non-resident attribute
                using (Stream s = ntfs.OpenFile(@"file", FileMode.Create, FileAccess.ReadWrite))
                {
                    byte[] data = new byte[(int)ntfs.ClusterSize];
                    data[0] = 0xAE;
                    data[1] = 0x3F;
                    data[2] = 0x8D;
                    s.Write(data, 0, (int)ntfs.ClusterSize);
                }

                var extents = ntfs.PathToExtents("file");
                Assert.Equal(1, extents.Length);
                Assert.Equal(ntfs.ClusterSize, extents[0].Length);

                ms.Position = extents[0].Start;
                Assert.Equal(0xAE, ms.ReadByte());
                Assert.Equal(0x3F, ms.ReadByte());
                Assert.Equal(0x8D, ms.ReadByte());


                // Check resident attribute
                using (Stream s = ntfs.OpenFile(@"file2", FileMode.Create, FileAccess.ReadWrite))
                {
                    s.WriteByte(0xBA);
                    s.WriteByte(0x82);
                    s.WriteByte(0x2C);
                }
                extents = ntfs.PathToExtents("file2");
                Assert.Equal(1, extents.Length);
                Assert.Equal(3, extents[0].Length);

                byte[] read = new byte[100];
                ms.Position = extents[0].Start;
                ms.Read(read, 0, 100);

                Assert.Equal(0xBA, read[0]);
                Assert.Equal(0x82, read[1]);
                Assert.Equal(0x2C, read[2]);
            }
        }
Beispiel #12
0
        /// <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
            }
        }
Beispiel #13
0
        // 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);
            }
        }
Beispiel #14
0
        protected override void DoRun()
        {
            if (DiskSize <= 0)
            {
                DisplayHelp();
                return;
            }

            using (VirtualDisk sourceDisk = VirtualDisk.OpenDisk(_sourceFile.Value, FileAccess.Read, UserName, Password))
                using (VirtualDisk destDisk = VirtualDisk.CreateDisk(OutputDiskType, OutputDiskVariant, _destFile.Value, DiskParameters, UserName, Password))
                {
                    if (destDisk is DiscUtils.Vhd.Disk)
                    {
                        ((DiscUtils.Vhd.Disk)destDisk).AutoCommitFooter = false;
                    }

                    // Copy the MBR from the source disk, and invent a new signature for this new disk
                    destDisk.SetMasterBootRecord(sourceDisk.GetMasterBootRecord());
                    destDisk.Signature = new Random().Next();

                    SparseStream   sourcePartStream = SparseStream.FromStream(sourceDisk.Partitions[0].Open(), Ownership.None);
                    NtfsFileSystem sourceNtfs       = new NtfsFileSystem(sourcePartStream);

                    // Copy the OS boot code into memory, so we can apply it when formatting the new disk
                    byte[] bootCode;
                    using (Stream bootStream = sourceNtfs.OpenFile("$Boot", FileMode.Open, FileAccess.Read))
                    {
                        bootCode = new byte[bootStream.Length];
                        int totalRead = 0;
                        while (totalRead < bootCode.Length)
                        {
                            totalRead += bootStream.Read(bootCode, totalRead, bootCode.Length - totalRead);
                        }
                    }

                    // Partition the new disk with a single NTFS partition
                    BiosPartitionTable.Initialize(destDisk, WellKnownPartitionType.WindowsNtfs);
                    VolumeManager volMgr = new VolumeManager(destDisk);

                    string label = _labelSwitch.IsPresent ? _labelSwitch.Value : sourceNtfs.VolumeLabel;
                    using (NtfsFileSystem destNtfs = NtfsFileSystem.Format(volMgr.GetLogicalVolumes()[0], label, bootCode))
                    {
                        destNtfs.SetSecurity(@"\", sourceNtfs.GetSecurity(@"\"));
                        destNtfs.NtfsOptions.ShortNameCreation = ShortFileNameOption.Disabled;

                        sourceNtfs.NtfsOptions.HideHiddenFiles = false;
                        sourceNtfs.NtfsOptions.HideSystemFiles = false;
                        CopyFiles(sourceNtfs, destNtfs, @"\", true);

                        if (destNtfs.FileExists(@"\boot\BCD"))
                        {
                            // Force all boot entries in the BCD to point to the newly created NTFS partition - does _not_ cope with
                            // complex multi-volume / multi-boot scenarios at all.
                            using (Stream bcdStream = destNtfs.OpenFile(@"\boot\BCD", FileMode.Open, FileAccess.ReadWrite))
                            {
                                using (RegistryHive hive = new RegistryHive(bcdStream))
                                {
                                    Store store = new Store(hive.Root);
                                    foreach (var obj in store.Objects)
                                    {
                                        foreach (var elem in obj.Elements)
                                        {
                                            if (elem.Format == DiscUtils.BootConfig.ElementFormat.Device)
                                            {
                                                elem.Value = DiscUtils.BootConfig.ElementValue.ForDevice(elem.Value.ParentObject, volMgr.GetPhysicalVolumes()[0]);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
        }