public static void Test(string path, long size)
        {
            int bytesPerCluster = 512;

            while (bytesPerCluster <= 65536)
            {
                string          volumeLabel = "FormatTest_" + bytesPerCluster.ToString();
                VirtualHardDisk disk        = VirtualHardDisk.CreateFixedDisk(path, size);
                disk.ExclusiveLock();
                Partition partition = CreatePrimaryPartition(disk);
                NTFSVolumeCreator.Format(partition, bytesPerCluster, volumeLabel);
                disk.ReleaseLock();
                VHDMountHelper.MountVHD(path);
                string driveName = MountHelper.WaitForDriveToMount(volumeLabel);
                if (driveName == null)
                {
                    throw new Exception("Timeout waiting for volume to mount");
                }
                bool isErrorFree = ChkdskHelper.Chkdsk(driveName);
                if (!isErrorFree)
                {
                    throw new InvalidDataException("CHKDSK reported errors");
                }
                VHDMountHelper.UnmountVHD(path);
                File.Delete(path);

                bytesPerCluster = bytesPerCluster * 2;
            }
        }
        private static void TestCreateAndDeleteFiles(string path, long size, int count)
        {
            int bytesPerCluster = 512;

            while (bytesPerCluster <= 65536)
            {
                string          volumeLabel = "CreateFilesTest_" + bytesPerCluster.ToString();
                VirtualHardDisk disk        = VirtualHardDisk.CreateFixedDisk(path, size);
                disk.ExclusiveLock();
                Partition  partition     = NTFSFormatTests.CreatePrimaryPartition(disk);
                NTFSVolume volume        = NTFSVolumeCreator.Format(partition, bytesPerCluster, volumeLabel);
                string     directoryName = "Directory";
                CreateFiles(volume, directoryName, count);
                disk.ReleaseLock();

                VHDMountHelper.MountVHD(path);
                string driveName = MountHelper.WaitForDriveToMount(volumeLabel);
                if (driveName == null)
                {
                    throw new Exception("Timeout waiting for volume to mount");
                }
                bool isErrorFree = ChkdskHelper.Chkdsk(driveName);
                if (!isErrorFree)
                {
                    throw new InvalidDataException("CHKDSK reported errors");
                }

                if (count != Directory.GetFiles(driveName + directoryName).Length)
                {
                    throw new InvalidDataException("Test failed");
                }
                VHDMountHelper.UnmountVHD(path);
                disk.ExclusiveLock();
                volume = new NTFSVolume(partition);
                DeleteFiles(volume, directoryName, count);
                disk.ReleaseLock();
                VHDMountHelper.MountVHD(path);
                isErrorFree = ChkdskHelper.Chkdsk(driveName);
                if (!isErrorFree)
                {
                    throw new InvalidDataException("CHKDSK reported errors");
                }

                if (Directory.GetFiles(driveName + directoryName).Length > 0)
                {
                    throw new InvalidDataException("Test failed");
                }
                VHDMountHelper.UnmountVHD(path);
                File.Delete(path);

                bytesPerCluster = bytesPerCluster * 2;
            }
        }
        private static void TestMove(string path, long size)
        {
            int bytesPerCluster = 512;

            while (bytesPerCluster <= 65536)
            {
                string          volumeLabel = "MoveTest_" + bytesPerCluster.ToString();
                VirtualHardDisk disk        = VirtualHardDisk.CreateFixedDisk(path, size);
                disk.ExclusiveLock();
                Partition  partition = NTFSFormatTests.CreatePrimaryPartition(disk);
                NTFSVolume volume    = NTFSVolumeCreator.Format(partition, bytesPerCluster, volumeLabel);

                string     directory1Name   = "Directory1";
                string     directory2Name   = "Directory2";
                FileRecord directory1Record = volume.CreateFile(NTFSVolume.RootDirSegmentReference, directory1Name, true);
                FileRecord directory2Record = volume.CreateFile(NTFSVolume.RootDirSegmentReference, directory2Name, true);
                string     fileNameBefore   = "Test1.txt";
                string     fileNameAfter    = "Test2.txt";
                FileRecord fileRecord       = volume.CreateFile(directory1Record.BaseSegmentReference, fileNameBefore, false);
                NTFSFile   file             = new NTFSFile(volume, fileRecord);
                byte[]     fileData         = System.Text.Encoding.ASCII.GetBytes("Test");
                file.Data.WriteBytes(0, fileData);
                volume.UpdateFileRecord(fileRecord);
                volume.MoveFile(fileRecord, directory2Record.BaseSegmentReference, fileNameAfter);
                disk.ReleaseLock();
                VHDMountHelper.MountVHD(path);
                string driveName = MountHelper.WaitForDriveToMount(volumeLabel);
                if (driveName == null)
                {
                    throw new Exception("Timeout waiting for volume to mount");
                }
                bool isErrorFree = ChkdskHelper.Chkdsk(driveName);
                if (!isErrorFree)
                {
                    throw new InvalidDataException("CHKDSK reported errors");
                }
                byte[] bytesRead = File.ReadAllBytes(driveName + directory2Name + "\\" + fileNameAfter);
                if (!ByteUtils.AreByteArraysEqual(fileData, bytesRead))
                {
                    throw new InvalidDataException("Test failed");
                }
                VHDMountHelper.UnmountVHD(path);
                File.Delete(path);

                bytesPerCluster = bytesPerCluster * 2;
            }
        }
Example #4
0
        public static void CreateVolumeWithPendingFileCreation(string path, long size, int bytesPerCluster, string volumeLabel, string fileName, byte[] fileData)
        {
            VirtualHardDisk disk = VirtualHardDisk.CreateFixedDisk(path, size);

            disk.ExclusiveLock();
            Partition         partition         = NTFSFormatTests.CreatePrimaryPartition(disk);
            NTFSVolume        volume            = NTFSVolumeCreator.Format(partition, bytesPerCluster, volumeLabel);
            long              segmentNumber     = MasterFileTable.FirstUserSegmentNumber;
            FileNameRecord    fileNameRecord    = new FileNameRecord(MasterFileTable.RootDirSegmentReference, fileName, false, DateTime.Now);
            FileRecordSegment fileRecordSegment = CreateFileRecordSegment(segmentNumber, fileNameRecord, fileData);

            ulong dataStreamOffset = (ulong)(segmentNumber * volume.BytesPerFileRecordSegment);

            byte[] redoData = fileRecordSegment.GetBytes(volume.BytesPerFileRecordSegment, volume.MinorVersion, false);
            MftSegmentReference mftFileReference = new MftSegmentReference(0, 1);
            AttributeRecord     mftDataRecord    = volume.GetFileRecord(mftFileReference).GetAttributeRecord(AttributeType.Data, String.Empty);
            AttributeRecord     mftBitmapRecord  = volume.GetFileRecord(mftFileReference).GetAttributeRecord(AttributeType.Bitmap, String.Empty);
            uint transactionID = volume.LogClient.AllocateTransactionID();

            volume.LogClient.WriteLogRecord(mftFileReference, mftDataRecord, dataStreamOffset, volume.BytesPerFileRecordSegment, NTFSLogOperation.InitializeFileRecordSegment, redoData, NTFSLogOperation.Noop, new byte[0], transactionID);
            long        bitmapVCN          = segmentNumber / (volume.BytesPerCluster * 8);
            int         bitOffsetInCluster = (int)(segmentNumber % (volume.BytesPerCluster * 8));
            BitmapRange bitmapRange        = new BitmapRange((uint)bitOffsetInCluster, 1);
            ulong       bitmapStreamOffset = (ulong)(bitmapVCN * volume.BytesPerCluster);

            volume.LogClient.WriteLogRecord(mftFileReference, mftBitmapRecord, bitmapStreamOffset, volume.BytesPerCluster, NTFSLogOperation.SetBitsInNonResidentBitMap, bitmapRange.GetBytes(), NTFSLogOperation.Noop, new byte[0], transactionID);

            FileRecord parentDirectoryRecord = volume.GetFileRecord(MasterFileTable.RootDirSegmentReference);
            IndexData  parentDirectoryIndex  = new IndexData(volume, parentDirectoryRecord, AttributeType.FileName);

            byte[]      fileNameRecordBytes   = fileNameRecord.GetBytes();
            long        leafRecordVBN         = 0;
            IndexRecord leafRecord            = parentDirectoryIndex.ReadIndexRecord(leafRecordVBN);
            ulong       indexAllocationOffset = (ulong)parentDirectoryIndex.ConvertToDataOffset(leafRecordVBN);
            int         insertIndex           = CollationHelper.FindIndexForSortedInsert(leafRecord.IndexEntries, fileNameRecordBytes, CollationRule.Filename);
            int         insertOffset          = leafRecord.GetEntryOffset(volume.BytesPerIndexRecord, insertIndex);

            AttributeRecord rootDirIndexAllocation = volume.GetFileRecord(MasterFileTable.RootDirSegmentReference).GetAttributeRecord(AttributeType.IndexAllocation, IndexHelper.GetIndexName(AttributeType.FileName));
            IndexEntry      indexEntry             = new IndexEntry(fileRecordSegment.SegmentReference, fileNameRecord.GetBytes());

            volume.LogClient.WriteLogRecord(MasterFileTable.RootDirSegmentReference, rootDirIndexAllocation, indexAllocationOffset, volume.BytesPerIndexRecord, 0, insertOffset, NTFSLogOperation.AddIndexEntryToAllocationBuffer, indexEntry.GetBytes(), NTFSLogOperation.Noop, new byte[0], transactionID, false);

            volume.LogClient.WriteForgetTransactionRecord(transactionID, true);
            disk.ReleaseLock();
        }
        private void btnOK_Click(object sender, EventArgs e)
        {
            string path = txtFilePath.Text;
            long   size = (long)numericDiskSize.Value * 1024 * 1024;

            if (path == String.Empty)
            {
                MessageBox.Show("Please choose file location", "Error");
                return;
            }
            m_isWorking = true;
            new Thread(delegate()
            {
                DiskImage diskImage;
                try
                {
                    diskImage = VirtualHardDisk.CreateFixedDisk(path, size);
                }
                catch (IOException ex)
                {
                    this.Invoke((MethodInvoker) delegate()
                    {
                        MessageBox.Show("Failed to create the disk: " + ex.Message, "Error");
                        txtFilePath.Enabled     = true;
                        btnBrowse.Enabled       = true;
                        numericDiskSize.Enabled = true;
                        btnOK.Enabled           = true;
                        btnCancel.Enabled       = true;
                    });
                    m_isWorking = false;
                    return;
                }
                bool isLocked = diskImage.ExclusiveLock();
                if (!isLocked)
                {
                    this.Invoke((MethodInvoker) delegate()
                    {
                        MessageBox.Show("Cannot lock the disk image for exclusive access", "Error");
                        txtFilePath.Enabled     = true;
                        btnBrowse.Enabled       = true;
                        numericDiskSize.Enabled = true;
                        btnOK.Enabled           = true;
                        btnCancel.Enabled       = true;
                    });
                    m_isWorking = false;
                    return;
                }
                m_diskImage = diskImage;
                m_isWorking = false;
                this.Invoke((MethodInvoker) delegate()
                {
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                });
            }).Start();
            txtFilePath.Enabled     = false;
            btnBrowse.Enabled       = false;
            numericDiskSize.Enabled = false;
            btnOK.Enabled           = false;
            btnCancel.Enabled       = false;
        }
Example #6
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (m_isBusy)
            {
                btnStart.Enabled     = false;
                btnStart.Text        = "Stopping";
                groupOptions.Enabled = false;
                Thread thread = new Thread(delegate()
                {
                    m_diskCopier.Abort = true;
                    while (m_isBusy)
                    {
                        Thread.Sleep(100);
                    }
                    if (!m_isClosing)
                    {
                        this.Invoke((MethodInvoker) delegate
                        {
                            EnableUI();
                            btnStart.Enabled = true;
                        });
                    }
                });
                thread.Start();
            }
            else
            {
                if (comboSourceDisk.SelectedItem == null)
                {
                    return;
                }
                int  sourceDiskIndex = ((KeyValuePair <int, string>)comboSourceDisk.SelectedItem).Key;
                int  targetDiskIndex = ((KeyValuePair <int, string>)comboTargetDisk.SelectedItem).Key;
                Disk sourceDisk      = null;
                Disk targetDisk      = null;
                if (sourceDiskIndex == -1)
                {
                    string path = openVirtualDiskFileDialog.FileName;
                    try
                    {
                        sourceDisk = new VirtualHardDisk(path, true);
                    }
                    catch (IOException ex)
                    {
                        MessageBox.Show("Failed to open the virtual disk: " + ex.Message, "Error");
                        return;
                    }
                }
                else
                {
                    try
                    {
                        sourceDisk = new PhysicalDisk(sourceDiskIndex);
                    }
                    catch (DriveNotFoundException)
                    {
                        MessageBox.Show("Source disk not found", "Error");
                        return;
                    }
                }

                if (targetDiskIndex == -1)
                {
                    string path = saveVirtualDiskFileDialog.FileName;;
                    try
                    {
                        if (chkWriteZeros.Checked)
                        {
                            targetDisk = VirtualHardDisk.CreateFixedDisk(path, sourceDisk.Size);
                        }
                        else
                        {
                            targetDisk = VirtualHardDisk.CreateDynamicDisk(path, sourceDisk.Size);
                        }
                    }
                    catch (IOException ex)
                    {
                        MessageBox.Show("Failed to create the virtual disk: " + ex.Message, "Error");
                        return;
                    }
                }
                else
                {
                    try
                    {
                        targetDisk = new PhysicalDisk(targetDiskIndex);
                    }
                    catch (DriveNotFoundException)
                    {
                        MessageBox.Show("Target disk not found", "Error");
                        return;
                    }
                }
                DisableUI();
                Thread thread = new Thread(delegate()
                {
                    m_isBusy = true;
                    CopyDisk(sourceDisk, targetDisk);
                    m_isBusy = false;
                    if (m_isClosing)
                    {
                        this.Invoke((MethodInvoker) delegate
                        {
                            this.Close();
                        });
                    }
                    else
                    {
                        this.Invoke((MethodInvoker) delegate
                        {
                            EnableUI();
                        });
                    }
                });
                thread.Start();
            }
        }
Example #7
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

            this.Text           += " v" + version.ToString(3);
            m_server.OnLogEntry += Program.OnLogEntry;

            List <IPAddress> localIPs = GetHostIPAddresses();
            KeyValuePairList <string, IPAddress> list = new KeyValuePairList <string, IPAddress>();

            list.Add("Any", IPAddress.Any);
            foreach (IPAddress address in localIPs)
            {
                list.Add(address.ToString(), address);
            }
            comboIPAddress.DataSource    = list;
            comboIPAddress.DisplayMember = "Key";
            comboIPAddress.ValueMember   = "Value";
            lblStatus.Text = "Author: Tal Aloni ([email protected])";
#if Win32
            if (!SecurityHelper.IsAdministrator())
            {
                lblStatus.Text = "Some features require administrator privileges and have been disabled";
            }
#endif
            //test
            string[] args = Environment.GetCommandLineArgs();
            if (args.Length > 1)
            {
                //to do

                /*
                 * if (args[0].Equals("DiskImage", StringComparison.OrdinalIgnoreCase)) { m_disks.Add(DiskImage.GetDiskImage(args[2], false)); }
                 */
            }
            if (System.IO.File.Exists("config.xml") && args.Length <= 1)
            {
                XmlDocument XmlDocObj = new XmlDocument();
                XmlDocObj.Load("config.xml");
                XmlNode node            = XmlDocObj.SelectSingleNode("//target");
                string  targetname      = "";
                string  targetpath      = "";
                string  targettype      = "";
                string  targetsize      = "";
                string  targetdiskindex = "";
                if (node.Attributes["name"] != null)
                {
                    targetname = node.Attributes["name"].Value;
                }
                if (node.Attributes["path"] != null)
                {
                    targetpath = node.Attributes["path"].Value;
                }
                if (node.Attributes["class"] != null)
                {
                    targettype = node.Attributes["class"].Value;
                }
                if (node.Attributes["size"] != null)
                {
                    targetsize = node.Attributes["size"].Value;
                }
                if (node.Attributes["index"] != null)
                {
                    targetdiskindex = node.Attributes["index"].Value;
                }
                if (targetname != "")
                {
                    //
                    List <Disk> m_disks = new List <Disk>();
                    if (targettype.Equals("RAMDisk", StringComparison.OrdinalIgnoreCase))
                    {
                        m_disks.Add(new RAMDisk(int.Parse(targetsize) * 1024 * 1024));
                    }
                    if (targettype.Equals("DiskImage", StringComparison.OrdinalIgnoreCase))
                    {
                        m_disks.Add(DiskImage.GetDiskImage(targetpath, false));
                    }
                    if (targettype.Equals("createDiskImage", StringComparison.OrdinalIgnoreCase))
                    {
                        m_disks.Add(VirtualHardDisk.CreateFixedDisk(targetpath, long.Parse(targetsize) * 1024 * 1024));
                    }
                    if (targettype.Equals("createRawDiskImage", StringComparison.OrdinalIgnoreCase))
                    {
                        m_disks.Add(RawDiskImage.Create(targetpath, long.Parse(targetsize) * 1024 * 1024));
                    }
                    if (targettype.Equals("PhysicalDisk", StringComparison.OrdinalIgnoreCase))
                    {
                        m_disks.Add(new PhysicalDisk(int.Parse(targetdiskindex)));
                    }
                    ISCSITarget target = new ISCSITarget(targetname, m_disks);
                    ((SCSI.VirtualSCSITarget)target.SCSITarget).OnLogEntry += Program.OnLogEntry;
                    target.OnAuthorizationRequest += new EventHandler <AuthorizationRequestArgs>(ISCSITarget_OnAuthorizationRequest);
                    target.OnSessionTermination   += new EventHandler <SessionTerminationArgs>(ISCSITarget_OnSessionTermination);
                    m_targets.Add(target);
                    //
                    try
                    {
                        m_server.AddTarget(target);
                    }
                    catch (ArgumentException ex)
                    {
                        MessageBox.Show(ex.Message, "Error");
                        return;
                    }
                    listTargets.Items.Add(target.TargetName);
                }
            }
        }