diff --git a/DiscImageChef.Core/ChangeLog b/DiscImageChef.Core/ChangeLog index 92c941d96..083974a2b 100644 --- a/DiscImageChef.Core/ChangeLog +++ b/DiscImageChef.Core/ChangeLog @@ -1,3 +1,13 @@ +2017-05-27 Natalia Portillo + + * DataFile.cs: + * ATA.cs: + * NVMe.cs: + * SCSI.cs: + * DiscImageChef.Core.csproj: + * SecureDigital.cs: Refactor: Move dumping code, and misc file + writing code, to Core. + 2017-05-27 Natalia Portillo * Statistics.cs: diff --git a/DiscImageChef.Core/DataFile.cs b/DiscImageChef.Core/DataFile.cs new file mode 100644 index 000000000..7ba16563f --- /dev/null +++ b/DiscImageChef.Core/DataFile.cs @@ -0,0 +1,109 @@ +// /*************************************************************************** +// The Disc Image Chef +// ---------------------------------------------------------------------------- +// +// Filename : DataFile.cs +// Version : 1.0 +// Author(s) : Natalia Portillo +// +// Component : Component +// +// Revision : $Revision$ +// Last change by : $Author$ +// Date : $Date$ +// +// --[ Description ] ---------------------------------------------------------- +// +// Description +// +// --[ License ] -------------------------------------------------------------- +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . +// +// ---------------------------------------------------------------------------- +// Copyright (C) 2011-2015 Claunia.com +// ****************************************************************************/ +// //$Id$ +using System; +using System.IO; +using DiscImageChef.Console; + +namespace DiscImageChef.Core +{ + public class DataFile + { + static FileStream dataFs; + + public DataFile(string outputFile) + { + dataFs = new FileStream(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite); + } + + public void Close() + { + if(dataFs != null) + dataFs.Close(); + } + + public int Read(byte[] array, int offset, int count) + { + return dataFs.Read(array, offset, count); + } + + public long Seek(long offset, SeekOrigin origin) + { + return dataFs.Seek(offset, origin); + } + + public void Write(byte[] data) + { + dataFs.Write(data, 0, data.Length); + } + + public void WriteAt(byte[] data, ulong block, uint blockSize) + { + dataFs.Seek((long)(block * blockSize), SeekOrigin.Begin); + dataFs.Write(data, 0, data.Length); + } + + public static void WriteTo(string who, string outputPrefix, string outputSuffix, string what, byte[] data) + { + if(!string.IsNullOrEmpty(outputPrefix) && !string.IsNullOrEmpty(outputSuffix)) + WriteTo(who, outputPrefix + outputSuffix, data, what); + } + + public static void WriteTo(string who, string filename, byte[] data, string whatWriting = null) + { + if(!string.IsNullOrEmpty(filename)) + { + if(!File.Exists(filename)) + { + try + { + DicConsole.DebugWriteLine(who, "Writing " + whatWriting + " to {0}", filename); + FileStream outputFs = new FileStream(filename, FileMode.CreateNew); + outputFs.Write(data, 0, data.Length); + outputFs.Close(); + } + catch + { + DicConsole.ErrorWriteLine("Unable to write file {0}", filename); + } + } + else + DicConsole.ErrorWriteLine("Not overwriting file {0}", filename); + } + } + } +} diff --git a/DiscImageChef.Core/Devices/Dumping/ATA.cs b/DiscImageChef.Core/Devices/Dumping/ATA.cs new file mode 100644 index 000000000..247e13745 --- /dev/null +++ b/DiscImageChef.Core/Devices/Dumping/ATA.cs @@ -0,0 +1,919 @@ +// /*************************************************************************** +// The Disc Image Chef +// ---------------------------------------------------------------------------- +// +// Filename : ATA.cs +// Version : 1.0 +// Author(s) : Natalia Portillo +// +// Component : Component +// +// Revision : $Revision$ +// Last change by : $Author$ +// Date : $Date$ +// +// --[ Description ] ---------------------------------------------------------- +// +// Description +// +// --[ License ] -------------------------------------------------------------- +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . +// +// ---------------------------------------------------------------------------- +// Copyright (C) 2011-2015 Claunia.com +// ****************************************************************************/ +// //$Id$ +using System; +using System.Collections.Generic; +using System.IO; +using DiscImageChef.CommonTypes; +using DiscImageChef.Console; +using DiscImageChef.Core.Logging; +using DiscImageChef.Decoders.PCMCIA; +using DiscImageChef.Devices; +using DiscImageChef.Filesystems; +using DiscImageChef.Filters; +using DiscImageChef.ImagePlugins; +using DiscImageChef.PartPlugins; +using Schemas; + +namespace DiscImageChef.Core.Devices.Dumping +{ + public class ATA + { + public static void Dump(Device dev, string devicePath, string outputPrefix, ushort retryPasses, bool force, bool dumpRaw, bool persistent, bool stopOnError) + { + bool aborted; + MHDDLog mhddLog; + IBGLog ibgLog; + + if(dumpRaw) + { + DicConsole.ErrorWriteLine("Raw dumping not yet supported in ATA devices."); + + if(force) + DicConsole.ErrorWriteLine("Continuing..."); + else + { + DicConsole.ErrorWriteLine("Aborting..."); + return; + } + } + + byte[] cmdBuf; + bool sense; + ulong blocks = 0; + uint blockSize = 512; + ushort currentProfile = 0x0001; + Decoders.ATA.AtaErrorRegistersCHS errorChs; + Decoders.ATA.AtaErrorRegistersLBA28 errorLba; + Decoders.ATA.AtaErrorRegistersLBA48 errorLba48; + bool lbaMode = false; + byte heads = 0, sectors = 0; + ushort cylinders = 0; + uint timeout = 5; + double duration; + + sense = dev.AtaIdentify(out cmdBuf, out errorChs); + if(!sense && Decoders.ATA.Identify.Decode(cmdBuf).HasValue) + { + Decoders.ATA.Identify.IdentifyDevice ataId = Decoders.ATA.Identify.Decode(cmdBuf).Value; + + CICMMetadataType sidecar = new CICMMetadataType(); + sidecar.BlockMedia = new BlockMediaType[1]; + sidecar.BlockMedia[0] = new BlockMediaType(); + + if(dev.IsUSB) + { + sidecar.BlockMedia[0].USB = new USBType(); + sidecar.BlockMedia[0].USB.ProductID = dev.USBProductID; + sidecar.BlockMedia[0].USB.VendorID = dev.USBVendorID; + sidecar.BlockMedia[0].USB.Descriptors = new DumpType(); + sidecar.BlockMedia[0].USB.Descriptors.Image = outputPrefix + ".usbdescriptors.bin"; + sidecar.BlockMedia[0].USB.Descriptors.Size = dev.USBDescriptors.Length; + sidecar.BlockMedia[0].USB.Descriptors.Checksums = Checksum.GetChecksums(dev.USBDescriptors).ToArray(); + DataFile.WriteTo("ATA Dump", sidecar.BlockMedia[0].USB.Descriptors.Image, dev.USBDescriptors); + } + + if(dev.IsPCMCIA) + { + sidecar.BlockMedia[0].PCMCIA = new PCMCIAType(); + sidecar.BlockMedia[0].PCMCIA.CIS = new DumpType(); + sidecar.BlockMedia[0].PCMCIA.CIS.Image = outputPrefix + ".cis.bin"; + sidecar.BlockMedia[0].PCMCIA.CIS.Size = dev.CIS.Length; + sidecar.BlockMedia[0].PCMCIA.CIS.Checksums = Checksum.GetChecksums(dev.CIS).ToArray(); + DataFile.WriteTo("ATA Dump", sidecar.BlockMedia[0].PCMCIA.CIS.Image, dev.CIS); + Decoders.PCMCIA.Tuple[] tuples = CIS.GetTuples(dev.CIS); + if(tuples != null) + { + foreach(Decoders.PCMCIA.Tuple tuple in tuples) + { + if(tuple.Code == TupleCodes.CISTPL_MANFID) + { + ManufacturerIdentificationTuple manfid = CIS.DecodeManufacturerIdentificationTuple(tuple); + + if(manfid != null) + { + sidecar.BlockMedia[0].PCMCIA.ManufacturerCode = manfid.ManufacturerID; + sidecar.BlockMedia[0].PCMCIA.CardCode = manfid.CardID; + sidecar.BlockMedia[0].PCMCIA.ManufacturerCodeSpecified = true; + sidecar.BlockMedia[0].PCMCIA.CardCodeSpecified = true; + } + } + else if(tuple.Code == TupleCodes.CISTPL_VERS_1) + { + Level1VersionTuple vers = CIS.DecodeLevel1VersionTuple(tuple); + + if(vers != null) + { + sidecar.BlockMedia[0].PCMCIA.Manufacturer = vers.Manufacturer; + sidecar.BlockMedia[0].PCMCIA.ProductName = vers.Product; + sidecar.BlockMedia[0].PCMCIA.Compliance = string.Format("{0}.{1}", vers.MajorVersion, vers.MinorVersion); + sidecar.BlockMedia[0].PCMCIA.AdditionalInformation = vers.AdditionalInformation; + } + } + } + } + } + + sidecar.BlockMedia[0].ATA = new ATAType(); + sidecar.BlockMedia[0].ATA.Identify = new DumpType(); + sidecar.BlockMedia[0].ATA.Identify.Image = outputPrefix + ".identify.bin"; + sidecar.BlockMedia[0].ATA.Identify.Size = cmdBuf.Length; + sidecar.BlockMedia[0].ATA.Identify.Checksums = Checksum.GetChecksums(cmdBuf).ToArray(); + DataFile.WriteTo("ATA Dump", sidecar.BlockMedia[0].ATA.Identify.Image, cmdBuf); + + if(ataId.CurrentCylinders > 0 && ataId.CurrentHeads > 0 && ataId.CurrentSectorsPerTrack > 0) + { + cylinders = ataId.CurrentCylinders; + heads = (byte)ataId.CurrentHeads; + sectors = (byte)ataId.CurrentSectorsPerTrack; + blocks = (ulong)(cylinders * heads * sectors); + } + + if((ataId.CurrentCylinders == 0 || ataId.CurrentHeads == 0 || ataId.CurrentSectorsPerTrack == 0) && + (ataId.Cylinders > 0 && ataId.Heads > 0 && ataId.SectorsPerTrack > 0)) + { + cylinders = ataId.Cylinders; + heads = (byte)ataId.Heads; + sectors = (byte)ataId.SectorsPerTrack; + blocks = (ulong)(cylinders * heads * sectors); + } + + if(ataId.Capabilities.HasFlag(Decoders.ATA.Identify.CapabilitiesBit.LBASupport)) + { + blocks = ataId.LBASectors; + lbaMode = true; + } + + if(ataId.CommandSet2.HasFlag(Decoders.ATA.Identify.CommandSetBit2.LBA48)) + { + blocks = ataId.LBA48Sectors; + lbaMode = true; + } + + uint physicalsectorsize = blockSize; + if((ataId.PhysLogSectorSize & 0x8000) == 0x0000 && + (ataId.PhysLogSectorSize & 0x4000) == 0x4000) + { + if((ataId.PhysLogSectorSize & 0x1000) == 0x1000) + { + if(ataId.LogicalSectorWords <= 255 || ataId.LogicalAlignment == 0xFFFF) + blockSize = 512; + else + blockSize = ataId.LogicalSectorWords * 2; + } + else + blockSize = 512; + + if((ataId.PhysLogSectorSize & 0x2000) == 0x2000) + { +#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created + physicalsectorsize = blockSize * (uint)Math.Pow(2, (double)(ataId.PhysLogSectorSize & 0xF)); +#pragma warning restore IDE0004 // Cast is necessary, otherwise incorrect value is created + } + else + physicalsectorsize = blockSize; + } + else + { + blockSize = 512; + physicalsectorsize = 512; + } + + bool ReadLba = false; + bool ReadRetryLba = false; + bool ReadDmaLba = false; + bool ReadDmaRetryLba = false; + + bool ReadLba48 = false; + bool ReadDmaLba48 = false; + + bool Read = false; + bool ReadRetry = false; + bool ReadDma = false; + bool ReadDmaRetry = false; + + sense = dev.Read(out cmdBuf, out errorChs, false, 0, 0, 1, 1, timeout, out duration); + Read = (!sense && (errorChs.status & 0x27) == 0 && errorChs.error == 0 && cmdBuf.Length > 0); + sense = dev.Read(out cmdBuf, out errorChs, true, 0, 0, 1, 1, timeout, out duration); + ReadRetry = (!sense && (errorChs.status & 0x27) == 0 && errorChs.error == 0 && cmdBuf.Length > 0); + sense = dev.ReadDma(out cmdBuf, out errorChs, false, 0, 0, 1, 1, timeout, out duration); + ReadDma = (!sense && (errorChs.status & 0x27) == 0 && errorChs.error == 0 && cmdBuf.Length > 0); + sense = dev.ReadDma(out cmdBuf, out errorChs, true, 0, 0, 1, 1, timeout, out duration); + ReadDmaRetry = (!sense && (errorChs.status & 0x27) == 0 && errorChs.error == 0 && cmdBuf.Length > 0); + + sense = dev.Read(out cmdBuf, out errorLba, false, 0, 1, timeout, out duration); + ReadLba = (!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); + sense = dev.Read(out cmdBuf, out errorLba, true, 0, 1, timeout, out duration); + ReadRetryLba = (!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); + sense = dev.ReadDma(out cmdBuf, out errorLba, false, 0, 1, timeout, out duration); + ReadDmaLba = (!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); + sense = dev.ReadDma(out cmdBuf, out errorLba, true, 0, 1, timeout, out duration); + ReadDmaRetryLba = (!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); + + sense = dev.Read(out cmdBuf, out errorLba48, 0, 1, timeout, out duration); + ReadLba48 = (!sense && (errorLba48.status & 0x27) == 0 && errorLba48.error == 0 && cmdBuf.Length > 0); + sense = dev.ReadDma(out cmdBuf, out errorLba48, 0, 1, timeout, out duration); + ReadDmaLba48 = (!sense && (errorLba48.status & 0x27) == 0 && errorLba48.error == 0 && cmdBuf.Length > 0); + + if(!lbaMode) + { + if(blocks > 0xFFFFFFF && !ReadLba48 && !ReadDmaLba48) + { + DicConsole.ErrorWriteLine("Device needs 48-bit LBA commands but I can't issue them... Aborting."); + return; + } + + if(!ReadLba && !ReadRetryLba && !ReadDmaLba && !ReadDmaRetryLba) + { + DicConsole.ErrorWriteLine("Device needs 28-bit LBA commands but I can't issue them... Aborting."); + return; + } + } + else + { + if(!Read && !ReadRetry && !ReadDma && !ReadDmaRetry) + { + DicConsole.ErrorWriteLine("Device needs CHS commands but I can't issue them... Aborting."); + return; + } + } + + if(ReadDmaLba48) + DicConsole.WriteLine("Using ATA READ DMA EXT command."); + else if(ReadLba48) + DicConsole.WriteLine("Using ATA READ EXT command."); + else if(ReadDmaRetryLba) + DicConsole.WriteLine("Using ATA READ DMA command with retries (LBA)."); + else if(ReadDmaLba) + DicConsole.WriteLine("Using ATA READ DMA command (LBA)."); + else if(ReadRetryLba) + DicConsole.WriteLine("Using ATA READ command with retries (LBA)."); + else if(ReadLba) + DicConsole.WriteLine("Using ATA READ command (LBA)."); + else if(ReadDmaRetry) + DicConsole.WriteLine("Using ATA READ DMA command with retries (CHS)."); + else if(ReadDma) + DicConsole.WriteLine("Using ATA READ DMA command (CHS)."); + else if(ReadRetry) + DicConsole.WriteLine("Using ATA READ command with retries (CHS)."); + else if(Read) + DicConsole.WriteLine("Using ATA READ command (CHS)."); + + uint blocksToRead = 64; + bool error = true; + while(lbaMode) + { + if(ReadDmaLba48) + { + sense = dev.ReadDma(out cmdBuf, out errorLba48, 0, (byte)blocksToRead, timeout, out duration); + error = !(!sense && (errorLba48.status & 0x27) == 0 && errorLba48.error == 0 && cmdBuf.Length > 0); + } + else if(ReadLba48) + { + sense = dev.Read(out cmdBuf, out errorLba48, 0, (byte)blocksToRead, timeout, out duration); + error = !(!sense && (errorLba48.status & 0x27) == 0 && errorLba48.error == 0 && cmdBuf.Length > 0); + } + else if(ReadDmaRetryLba) + { + sense = dev.ReadDma(out cmdBuf, out errorLba, true, 0, (byte)blocksToRead, timeout, out duration); + error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); + } + else if(ReadDmaLba) + { + sense = dev.ReadDma(out cmdBuf, out errorLba, false, 0, (byte)blocksToRead, timeout, out duration); + error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); + } + else if(ReadRetryLba) + { + sense = dev.Read(out cmdBuf, out errorLba, true, 0, (byte)blocksToRead, timeout, out duration); + error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); + } + else if(ReadLba) + { + sense = dev.Read(out cmdBuf, out errorLba, false, 0, (byte)blocksToRead, timeout, out duration); + error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); + } + + if(error) + blocksToRead /= 2; + + if(!error || blocksToRead == 1) + break; + } + + if(error && lbaMode) + { + DicConsole.ErrorWriteLine("Device error {0} trying to guess ideal transfer length.", dev.LastError); + return; + } + + ulong A = 0; // <3ms + ulong B = 0; // >=3ms, <10ms + ulong C = 0; // >=10ms, <50ms + ulong D = 0; // >=50ms, <150ms + ulong E = 0; // >=150ms, <500ms + ulong F = 0; // >=500ms + ulong errored = 0; + DateTime start; + DateTime end; + double totalDuration = 0; + double totalChkDuration = 0; + double currentSpeed = 0; + double maxSpeed = double.MinValue; + double minSpeed = double.MaxValue; + List unreadableSectors = new List(); + Checksum dataChk; + + aborted = false; + System.Console.CancelKeyPress += (sender, e) => + { + e.Cancel = aborted = true; + }; + + DataFile dumpFile; + + if(lbaMode) + { + DicConsole.WriteLine("Reading {0} sectors at a time.", blocksToRead); + + mhddLog = new MHDDLog(outputPrefix + ".mhddlog.bin", dev, blocks, blockSize, blocksToRead); + ibgLog = new IBGLog(outputPrefix + ".ibg", currentProfile); + dumpFile = new DataFile(outputPrefix + ".bin"); + + start = DateTime.UtcNow; + for(ulong i = 0; i < blocks; i += blocksToRead) + { + if(aborted) + break; + + double cmdDuration = 0; + + if((blocks - i) < blocksToRead) + blocksToRead = (byte)(blocks - i); + +#pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator + if(currentSpeed > maxSpeed && currentSpeed != 0) + maxSpeed = currentSpeed; + if(currentSpeed < minSpeed && currentSpeed != 0) + minSpeed = currentSpeed; +#pragma warning restore RECS0018 // Comparison of floating point numbers with equality operator + + DicConsole.Write("\rReading sector {0} of {1} ({2:F3} MiB/sec.)", i, blocks, currentSpeed); + + error = true; + byte status = 0, errorByte = 0; + + if(ReadDmaLba48) + { + sense = dev.ReadDma(out cmdBuf, out errorLba48, i, (byte)blocksToRead, timeout, out cmdDuration); + error = !(!sense && (errorLba48.status & 0x27) == 0 && errorLba48.error == 0 && cmdBuf.Length > 0); + status = errorLba48.status; + errorByte = errorLba48.error; + } + else if(ReadLba48) + { + sense = dev.Read(out cmdBuf, out errorLba48, i, (byte)blocksToRead, timeout, out cmdDuration); + error = !(!sense && (errorLba48.status & 0x27) == 0 && errorLba48.error == 0 && cmdBuf.Length > 0); + status = errorLba48.status; + errorByte = errorLba48.error; + } + else if(ReadDmaRetryLba) + { + sense = dev.ReadDma(out cmdBuf, out errorLba, true, (uint)i, (byte)blocksToRead, timeout, out cmdDuration); + error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); + status = errorLba.status; + errorByte = errorLba.error; + } + else if(ReadDmaLba) + { + sense = dev.ReadDma(out cmdBuf, out errorLba, false, (uint)i, (byte)blocksToRead, timeout, out cmdDuration); + error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); + status = errorLba.status; + errorByte = errorLba.error; + } + else if(ReadRetryLba) + { + sense = dev.Read(out cmdBuf, out errorLba, true, (uint)i, (byte)blocksToRead, timeout, out cmdDuration); + error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); + status = errorLba.status; + errorByte = errorLba.error; + } + else if(ReadLba) + { + sense = dev.Read(out cmdBuf, out errorLba, false, (uint)i, (byte)blocksToRead, timeout, out cmdDuration); + error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); + status = errorLba.status; + errorByte = errorLba.error; + } + + if(!error) + { + if(cmdDuration >= 500) + { + F += blocksToRead; + } + else if(cmdDuration >= 150) + { + E += blocksToRead; + } + else if(cmdDuration >= 50) + { + D += blocksToRead; + } + else if(cmdDuration >= 10) + { + C += blocksToRead; + } + else if(cmdDuration >= 3) + { + B += blocksToRead; + } + else + { + A += blocksToRead; + } + + mhddLog.Write(i, cmdDuration); + ibgLog.Write(i, currentSpeed * 1024); + dumpFile.Write(cmdBuf); + } + else + { + DicConsole.DebugWriteLine("Media-Scan", "ATA ERROR: {0} STATUS: {1}", errorByte, status); + errored += blocksToRead; + unreadableSectors.Add(i); + if(cmdDuration < 500) + mhddLog.Write(i, 65535); + else + mhddLog.Write(i, cmdDuration); + + ibgLog.Write(i, 0); + dumpFile.Write(new byte[blockSize * blocksToRead]); + } + +#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created + currentSpeed = ((double)blockSize * blocksToRead / (double)1048576) / (cmdDuration / (double)1000); +#pragma warning restore IDE0004 // Cast is necessary, otherwise incorrect value is created + GC.Collect(); + } + end = DateTime.Now; + DicConsole.WriteLine(); + mhddLog.Close(); +#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created + ibgLog.Close(dev, blocks, blockSize, (end - start).TotalSeconds, currentSpeed * 1024, (((double)blockSize * (double)(blocks + 1)) / 1024) / (totalDuration / 1000), devicePath); +#pragma warning restore IDE0004 // Cast is necessary, otherwise incorrect value is created + + #region Error handling + if(unreadableSectors.Count > 0 && !aborted) + { + List tmpList = new List(); + + foreach(ulong ur in unreadableSectors) + { + for(ulong i = ur; i < ur + blocksToRead; i++) + tmpList.Add(i); + } + + tmpList.Sort(); + + int pass = 0; + bool forward = true; + bool runningPersistent = false; + + unreadableSectors = tmpList; + + repeatRetryLba: + ulong[] tmpArray = unreadableSectors.ToArray(); + foreach(ulong badSector in tmpArray) + { + if(aborted) + break; + + double cmdDuration = 0; + + DicConsole.Write("\rRetrying sector {0}, pass {1}, {3}{2}", badSector, pass + 1, forward ? "forward" : "reverse", runningPersistent ? "recovering partial data, " : ""); + + if(ReadDmaLba48) + { + sense = dev.ReadDma(out cmdBuf, out errorLba48, badSector, 1, timeout, out cmdDuration); + error = !(!sense && (errorLba48.status & 0x27) == 0 && errorLba48.error == 0 && cmdBuf.Length > 0); + } + else if(ReadLba48) + { + sense = dev.Read(out cmdBuf, out errorLba48, badSector, 1, timeout, out cmdDuration); + error = !(!sense && (errorLba48.status & 0x27) == 0 && errorLba48.error == 0 && cmdBuf.Length > 0); + } + else if(ReadDmaRetryLba) + { + sense = dev.ReadDma(out cmdBuf, out errorLba, true, (uint)badSector, 1, timeout, out cmdDuration); + error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); + } + else if(ReadDmaLba) + { + sense = dev.ReadDma(out cmdBuf, out errorLba, false, (uint)badSector, 1, timeout, out cmdDuration); + error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); + } + else if(ReadRetryLba) + { + sense = dev.Read(out cmdBuf, out errorLba, true, (uint)badSector, 1, timeout, out cmdDuration); + error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); + } + else if(ReadLba) + { + sense = dev.Read(out cmdBuf, out errorLba, false, (uint)badSector, 1, timeout, out cmdDuration); + error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); + } + + totalDuration += cmdDuration; + + if(!error) + { + unreadableSectors.Remove(badSector); + dumpFile.WriteAt(cmdBuf, badSector, blockSize); + } + else if(runningPersistent) + dumpFile.WriteAt(cmdBuf, badSector, blockSize); + } + + if(pass < retryPasses && !aborted && unreadableSectors.Count > 0) + { + pass++; + forward = !forward; + unreadableSectors.Sort(); + unreadableSectors.Reverse(); + goto repeatRetryLba; + } + + DicConsole.WriteLine(); + } + #endregion Error handling LBA + } + else + { + mhddLog = new MHDDLog(outputPrefix + ".mhddlog.bin", dev, blocks, blockSize, blocksToRead); + ibgLog = new IBGLog(outputPrefix + ".ibg", currentProfile); + dumpFile = new DataFile(outputPrefix + ".bin"); + + ulong currentBlock = 0; + blocks = (ulong)(cylinders * heads * sectors); + start = DateTime.UtcNow; + for(ushort Cy = 0; Cy < cylinders; Cy++) + { + for(byte Hd = 0; Hd < heads; Hd++) + { + for(byte Sc = 1; Sc < sectors; Sc++) + { + if(aborted) + break; + + double cmdDuration = 0; + +#pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator + if(currentSpeed > maxSpeed && currentSpeed != 0) + maxSpeed = currentSpeed; + if(currentSpeed < minSpeed && currentSpeed != 0) + minSpeed = currentSpeed; +#pragma warning restore RECS0018 // Comparison of floating point numbers with equality operator + + DicConsole.Write("\rReading cylinder {0} head {1} sector {2} ({3:F3} MiB/sec.)", Cy, Hd, Sc, currentSpeed); + + error = true; + byte status = 0, errorByte = 0; + + if(ReadDmaRetry) + { + sense = dev.ReadDma(out cmdBuf, out errorChs, true, Cy, Hd, Sc, 1, timeout, out cmdDuration); + error = !(!sense && (errorChs.status & 0x27) == 0 && errorChs.error == 0 && cmdBuf.Length > 0); + status = errorChs.status; + errorByte = errorChs.error; + } + else if(ReadDma) + { + sense = dev.ReadDma(out cmdBuf, out errorChs, false, Cy, Hd, Sc, 1, timeout, out cmdDuration); + error = !(!sense && (errorChs.status & 0x27) == 0 && errorChs.error == 0 && cmdBuf.Length > 0); + status = errorChs.status; + errorByte = errorChs.error; + } + else if(ReadRetry) + { + sense = dev.Read(out cmdBuf, out errorChs, true, Cy, Hd, Sc, 1, timeout, out cmdDuration); + error = !(!sense && (errorChs.status & 0x27) == 0 && errorChs.error == 0 && cmdBuf.Length > 0); + status = errorChs.status; + errorByte = errorChs.error; + } + else if(Read) + { + sense = dev.Read(out cmdBuf, out errorChs, false, Cy, Hd, Sc, 1, timeout, out cmdDuration); + error = !(!sense && (errorChs.status & 0x27) == 0 && errorChs.error == 0 && cmdBuf.Length > 0); + status = errorChs.status; + errorByte = errorChs.error; + } + + totalDuration += cmdDuration; + + if(!error) + { + if(cmdDuration >= 500) + { + F += blocksToRead; + } + else if(cmdDuration >= 150) + { + E += blocksToRead; + } + else if(cmdDuration >= 50) + { + D += blocksToRead; + } + else if(cmdDuration >= 10) + { + C += blocksToRead; + } + else if(cmdDuration >= 3) + { + B += blocksToRead; + } + else + { + A += blocksToRead; + } + + mhddLog.Write(currentBlock, cmdDuration); + ibgLog.Write(currentBlock, currentSpeed * 1024); + dumpFile.Write(cmdBuf); + } + else + { + DicConsole.DebugWriteLine("Media-Scan", "ATA ERROR: {0} STATUS: {1}", errorByte, status); + errored += blocksToRead; + unreadableSectors.Add(currentBlock); + if(cmdDuration < 500) + mhddLog.Write(currentBlock, 65535); + else + mhddLog.Write(currentBlock, cmdDuration); + + ibgLog.Write(currentBlock, 0); + dumpFile.Write(new byte[blockSize]); + } + +#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created + currentSpeed = ((double)blockSize / (double)1048576) / (cmdDuration / (double)1000); +#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created + GC.Collect(); + + currentBlock++; + } + } + } + end = DateTime.Now; + DicConsole.WriteLine(); + mhddLog.Close(); +#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created + ibgLog.Close(dev, blocks, blockSize, (end - start).TotalSeconds, currentSpeed * 1024, (((double)blockSize * (double)(blocks + 1)) / 1024) / (totalDuration / 1000), devicePath); +#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created + } + dataChk = new Checksum(); + dumpFile.Seek(0, SeekOrigin.Begin); + blocksToRead = 500; + + for(ulong i = 0; i < blocks; i += blocksToRead) + { + if(aborted) + break; + + if((blocks - i) < blocksToRead) + blocksToRead = (byte)(blocks - i); + + DicConsole.Write("\rChecksumming sector {0} of {1} ({2:F3} MiB/sec.)", i, blocks, currentSpeed); + + DateTime chkStart = DateTime.UtcNow; + byte[] dataToCheck = new byte[blockSize * blocksToRead]; + dumpFile.Read(dataToCheck, 0, (int)(blockSize * blocksToRead)); + dataChk.Update(dataToCheck); + DateTime chkEnd = DateTime.UtcNow; + + double chkDuration = (chkEnd - chkStart).TotalMilliseconds; + totalChkDuration += chkDuration; + + currentSpeed = ((double)blockSize * blocksToRead / (double)1048576) / (chkDuration / (double)1000); + } + DicConsole.WriteLine(); + dumpFile.Close(); + end = DateTime.UtcNow; + + PluginBase plugins = new PluginBase(); + plugins.RegisterAllPlugins(); + ImagePlugin _imageFormat; + + FiltersList filtersList = new FiltersList(); + Filter inputFilter = filtersList.GetFilter(outputPrefix + ".bin"); + + if(inputFilter == null) + { + DicConsole.ErrorWriteLine("Cannot open file just created, this should not happen."); + return; + } + + _imageFormat = ImageFormat.Detect(inputFilter); + PartitionType[] xmlFileSysInfo = null; + + try + { + if(!_imageFormat.OpenImage(inputFilter)) + _imageFormat = null; + } + catch + { + _imageFormat = null; + } + + if(_imageFormat != null) + { + List partitions = new List(); + + foreach(PartPlugin _partplugin in plugins.PartPluginsList.Values) + { + List _partitions; + + if(_partplugin.GetInformation(_imageFormat, out _partitions)) + { + partitions.AddRange(_partitions); + Statistics.AddPartition(_partplugin.Name); + } + } + + if(partitions.Count > 0) + { + xmlFileSysInfo = new PartitionType[partitions.Count]; + for(int i = 0; i < partitions.Count; i++) + { + xmlFileSysInfo[i] = new PartitionType(); + xmlFileSysInfo[i].Description = partitions[i].PartitionDescription; + xmlFileSysInfo[i].EndSector = (int)(partitions[i].PartitionStartSector + partitions[i].PartitionSectors - 1); + xmlFileSysInfo[i].Name = partitions[i].PartitionName; + xmlFileSysInfo[i].Sequence = (int)partitions[i].PartitionSequence; + xmlFileSysInfo[i].StartSector = (int)partitions[i].PartitionStartSector; + xmlFileSysInfo[i].Type = partitions[i].PartitionType; + + List lstFs = new List(); + + foreach(Filesystem _plugin in plugins.PluginsList.Values) + { + try + { + if(_plugin.Identify(_imageFormat, partitions[i].PartitionStartSector, partitions[i].PartitionStartSector + partitions[i].PartitionSectors - 1)) + { + string foo; + _plugin.GetInformation(_imageFormat, partitions[i].PartitionStartSector, partitions[i].PartitionStartSector + partitions[i].PartitionSectors - 1, out foo); + lstFs.Add(_plugin.XmlFSType); + Statistics.AddFilesystem(_plugin.XmlFSType.Type); + } + } +#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body + catch +#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body + { + //DicConsole.DebugWriteLine("Dump-media command", "Plugin {0} crashed", _plugin.Name); + } + } + + if(lstFs.Count > 0) + xmlFileSysInfo[i].FileSystems = lstFs.ToArray(); + } + } + else + { + xmlFileSysInfo = new PartitionType[1]; + xmlFileSysInfo[0] = new PartitionType(); + xmlFileSysInfo[0].EndSector = (int)(blocks - 1); + xmlFileSysInfo[0].StartSector = 0; + + List lstFs = new List(); + + foreach(Filesystem _plugin in plugins.PluginsList.Values) + { + try + { + if(_plugin.Identify(_imageFormat, (blocks - 1), 0)) + { + string foo; + _plugin.GetInformation(_imageFormat, (blocks - 1), 0, out foo); + lstFs.Add(_plugin.XmlFSType); + Statistics.AddFilesystem(_plugin.XmlFSType.Type); + } + } +#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body + catch +#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body + { + //DicConsole.DebugWriteLine("Create-sidecar command", "Plugin {0} crashed", _plugin.Name); + } + } + + if(lstFs.Count > 0) + xmlFileSysInfo[0].FileSystems = lstFs.ToArray(); + } + } + + sidecar.BlockMedia[0].Checksums = dataChk.End().ToArray(); + string xmlDskTyp, xmlDskSubTyp; + if(dev.IsCompactFlash) + Metadata.MediaType.MediaTypeToString(MediaType.CompactFlash, out xmlDskTyp, out xmlDskSubTyp); + else if(dev.IsPCMCIA) + Metadata.MediaType.MediaTypeToString(MediaType.PCCardTypeI, out xmlDskTyp, out xmlDskSubTyp); + else + Metadata.MediaType.MediaTypeToString(MediaType.GENERIC_HDD, out xmlDskTyp, out xmlDskSubTyp); + sidecar.BlockMedia[0].DiskType = xmlDskTyp; + sidecar.BlockMedia[0].DiskSubType = xmlDskSubTyp; + // TODO: Implement device firmware revision + sidecar.BlockMedia[0].Image = new ImageType(); + sidecar.BlockMedia[0].Image.format = "Raw disk image (sector by sector copy)"; + sidecar.BlockMedia[0].Image.Value = outputPrefix + ".bin"; + sidecar.BlockMedia[0].Interface = "ATA"; + sidecar.BlockMedia[0].LogicalBlocks = (long)blocks; + sidecar.BlockMedia[0].PhysicalBlockSize = (int)physicalsectorsize; + sidecar.BlockMedia[0].LogicalBlockSize = (int)blockSize; + sidecar.BlockMedia[0].Manufacturer = dev.Manufacturer; + sidecar.BlockMedia[0].Model = dev.Model; + sidecar.BlockMedia[0].Serial = dev.Serial; + sidecar.BlockMedia[0].Size = (long)(blocks * blockSize); + if(xmlFileSysInfo != null) + sidecar.BlockMedia[0].FileSystemInformation = xmlFileSysInfo; + if(cylinders > 0 && heads > 0 && sectors > 0) + { + sidecar.BlockMedia[0].Cylinders = cylinders; + sidecar.BlockMedia[0].CylindersSpecified = true; + sidecar.BlockMedia[0].Heads = heads; + sidecar.BlockMedia[0].HeadsSpecified = true; + sidecar.BlockMedia[0].SectorsPerTrack = sectors; + sidecar.BlockMedia[0].SectorsPerTrackSpecified = true; + } + + DicConsole.WriteLine(); + + DicConsole.WriteLine("Took a total of {0:F3} seconds ({1:F3} processing commands, {2:F3} checksumming).", (end - start).TotalSeconds, totalDuration / 1000, totalChkDuration / 1000); + DicConsole.WriteLine("Avegare speed: {0:F3} MiB/sec.", (((double)blockSize * (double)(blocks + 1)) / 1048576) / (totalDuration / 1000)); + DicConsole.WriteLine("Fastest speed burst: {0:F3} MiB/sec.", maxSpeed); + DicConsole.WriteLine("Slowest speed burst: {0:F3} MiB/sec.", minSpeed); + DicConsole.WriteLine("{0} sectors could not be read.", unreadableSectors.Count); + if(unreadableSectors.Count > 0) + { + unreadableSectors.Sort(); + foreach(ulong bad in unreadableSectors) + DicConsole.WriteLine("Sector {0} could not be read", bad); + } + DicConsole.WriteLine(); + + if(!aborted) + { + DicConsole.WriteLine("Writing metadata sidecar"); + + FileStream xmlFs = new FileStream(outputPrefix + ".cicm.xml", + FileMode.Create); + + System.Xml.Serialization.XmlSerializer xmlSer = new System.Xml.Serialization.XmlSerializer(typeof(CICMMetadataType)); + xmlSer.Serialize(xmlFs, sidecar); + xmlFs.Close(); + } + + Statistics.AddMedia(MediaType.GENERIC_HDD, true); + } + else + DicConsole.ErrorWriteLine("Unable to communicate with ATA device."); + } + } +} diff --git a/DiscImageChef.Core/Devices/Dumping/NVMe.cs b/DiscImageChef.Core/Devices/Dumping/NVMe.cs new file mode 100644 index 000000000..1f38e15a0 --- /dev/null +++ b/DiscImageChef.Core/Devices/Dumping/NVMe.cs @@ -0,0 +1,50 @@ +// /*************************************************************************** +// The Disc Image Chef +// ---------------------------------------------------------------------------- +// +// Filename : NVMe.cs +// Version : 1.0 +// Author(s) : Natalia Portillo +// +// Component : Component +// +// Revision : $Revision$ +// Last change by : $Author$ +// Date : $Date$ +// +// --[ Description ] ---------------------------------------------------------- +// +// Description +// +// --[ License ] -------------------------------------------------------------- +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . +// +// ---------------------------------------------------------------------------- +// Copyright (C) 2011-2015 Claunia.com +// ****************************************************************************/ +// //$Id$ +using System; +using DiscImageChef.Devices; + +namespace DiscImageChef.Core.Devices.Dumping +{ + public static class NVMe + { + public static void Dump(Device dev, string devicePath, string outputPrefix, ushort retryPasses, bool force, bool dumpRaw, bool persistent, bool stopOnError) + { + throw new NotImplementedException("NVMe devices not yet supported."); + } + } +} diff --git a/DiscImageChef.Core/Devices/Dumping/SCSI.cs b/DiscImageChef.Core/Devices/Dumping/SCSI.cs new file mode 100644 index 000000000..431a2a650 --- /dev/null +++ b/DiscImageChef.Core/Devices/Dumping/SCSI.cs @@ -0,0 +1,3614 @@ +// /*************************************************************************** +// The Disc Image Chef +// ---------------------------------------------------------------------------- +// +// Filename : SCSI.cs +// Version : 1.0 +// Author(s) : Natalia Portillo +// +// Component : Component +// +// Revision : $Revision$ +// Last change by : $Author$ +// Date : $Date$ +// +// --[ Description ] ---------------------------------------------------------- +// +// Description +// +// --[ License ] -------------------------------------------------------------- +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . +// +// ---------------------------------------------------------------------------- +// Copyright (C) 2011-2015 Claunia.com +// ****************************************************************************/ +// //$Id$ +using System; +using System.Collections.Generic; +using System.IO; +using DiscImageChef.CommonTypes; +using DiscImageChef.Console; +using DiscImageChef.Core.Logging; +using DiscImageChef.Devices; +using DiscImageChef.Filesystems; +using DiscImageChef.Filters; +using DiscImageChef.ImagePlugins; +using DiscImageChef.PartPlugins; +using Schemas; + +namespace DiscImageChef.Core.Devices.Dumping +{ + public class SCSI + { + // TODO: Get cartridge serial number from Certance vendor EVPD + public static void Dump(Device dev, string devicePath, string outputPrefix, ushort retryPasses, bool force, bool dumpRaw, bool persistent, bool stopOnError) + { + bool aborted; + MHDDLog mhddLog; + IBGLog ibgLog; + byte[] cmdBuf = null; + byte[] senseBuf = null; + bool sense = false; + double duration; + ulong blocks = 0; + uint blockSize = 0; + byte[] tmpBuf; + MediaType dskType = MediaType.Unknown; + bool opticalDisc = false; + uint logicalBlockSize = 0; + uint physicalBlockSize = 0; + + if(dev.IsRemovable) + { + sense = dev.ScsiTestUnitReady(out senseBuf, dev.Timeout, out duration); + if(sense) + { + Decoders.SCSI.FixedSense? decSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf); + if(decSense.HasValue) + { + if(decSense.Value.ASC == 0x3A) + { + int leftRetries = 5; + while(leftRetries > 0) + { + DicConsole.WriteLine("\rWaiting for drive to become ready"); + System.Threading.Thread.Sleep(2000); + sense = dev.ScsiTestUnitReady(out senseBuf, dev.Timeout, out duration); + if(!sense) + break; + + leftRetries--; + } + + if(sense) + { + DicConsole.ErrorWriteLine("Please insert media in drive"); + return; + } + } + else if(decSense.Value.ASC == 0x04 && decSense.Value.ASCQ == 0x01) + { + int leftRetries = 10; + while(leftRetries > 0) + { + DicConsole.WriteLine("\rWaiting for drive to become ready"); + System.Threading.Thread.Sleep(2000); + sense = dev.ScsiTestUnitReady(out senseBuf, dev.Timeout, out duration); + if(!sense) + break; + + leftRetries--; + } + + if(sense) + { + DicConsole.ErrorWriteLine("Error testing unit was ready:\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); + return; + } + } + /*else if (decSense.Value.ASC == 0x29 && decSense.Value.ASCQ == 0x00) + { + if (!deviceReset) + { + deviceReset = true; + DicConsole.ErrorWriteLine("Device did reset, retrying..."); + goto retryTestReady; + } + + DicConsole.ErrorWriteLine("Error testing unit was ready:\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); + return; + }*/ + else + { + DicConsole.ErrorWriteLine("Error testing unit was ready:\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); + return; + } + } + else + { + DicConsole.ErrorWriteLine("Unknown testing unit was ready."); + return; + } + } + } + + if(dev.SCSIType == Decoders.SCSI.PeripheralDeviceTypes.DirectAccess || + dev.SCSIType == Decoders.SCSI.PeripheralDeviceTypes.MultiMediaDevice || + dev.SCSIType == Decoders.SCSI.PeripheralDeviceTypes.OCRWDevice || + dev.SCSIType == Decoders.SCSI.PeripheralDeviceTypes.OpticalDevice || + dev.SCSIType == Decoders.SCSI.PeripheralDeviceTypes.SimplifiedDevice || + dev.SCSIType == Decoders.SCSI.PeripheralDeviceTypes.WriteOnceDevice) + { + sense = dev.ReadCapacity(out cmdBuf, out senseBuf, dev.Timeout, out duration); + if(!sense) + { + blocks = (ulong)((cmdBuf[0] << 24) + (cmdBuf[1] << 16) + (cmdBuf[2] << 8) + (cmdBuf[3])); + blockSize = (uint)((cmdBuf[5] << 24) + (cmdBuf[5] << 16) + (cmdBuf[6] << 8) + (cmdBuf[7])); + } + + if(sense || blocks == 0xFFFFFFFF) + { + sense = dev.ReadCapacity16(out cmdBuf, out senseBuf, dev.Timeout, out duration); + + if(sense && blocks == 0) + { + // Not all MMC devices support READ CAPACITY, as they have READ TOC + if(dev.SCSIType != Decoders.SCSI.PeripheralDeviceTypes.MultiMediaDevice) + { + DicConsole.ErrorWriteLine("Unable to get media capacity"); + DicConsole.ErrorWriteLine("{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); + } + } + + if(!sense) + { + byte[] temp = new byte[8]; + + Array.Copy(cmdBuf, 0, temp, 0, 8); + Array.Reverse(temp); + blocks = BitConverter.ToUInt64(temp, 0); + blockSize = (uint)((cmdBuf[5] << 24) + (cmdBuf[5] << 16) + (cmdBuf[6] << 8) + (cmdBuf[7])); + } + } + + if(blocks != 0 && blockSize != 0) + { + blocks++; + DicConsole.WriteLine("Media has {0} blocks of {1} bytes/each. (for a total of {2} bytes)", + blocks, blockSize, blocks * (ulong)blockSize); + } + + logicalBlockSize = blockSize; + physicalBlockSize = blockSize; + } + + DateTime start; + DateTime end; + double totalDuration = 0; + double totalChkDuration = 0; + double currentSpeed = 0; + double maxSpeed = double.MinValue; + double minSpeed = double.MaxValue; + List unreadableSectors = new List(); + Checksum dataChk; + CICMMetadataType sidecar = new CICMMetadataType(); + + DataFile dumpFile = null; + + if(dev.SCSIType == Decoders.SCSI.PeripheralDeviceTypes.SequentialAccess) + { + if(dumpRaw) + throw new ArgumentException("Tapes cannot be dumped raw."); + + Decoders.SCSI.FixedSense? fxSense; + string strSense; + byte[] tapeBuf; + + dev.RequestSense(out senseBuf, dev.Timeout, out duration); + fxSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf, out strSense); + + if(fxSense.HasValue && fxSense.Value.SenseKey != Decoders.SCSI.SenseKeys.NoSense) + { + DicConsole.ErrorWriteLine("Drive has status error, please correct. Sense follows..."); + DicConsole.ErrorWriteLine("{0}", strSense); + return; + } + + // Not in BOM/P + if(fxSense.HasValue && fxSense.Value.ASC == 0x00 && fxSense.Value.ASCQ != 0x04) + { + DicConsole.Write("Rewinding, please wait..."); + // Rewind, let timeout apply + sense = dev.Rewind(out senseBuf, dev.Timeout, out duration); + + // Still rewinding? + // TODO: Pause? + do + { + DicConsole.Write("\rRewinding, please wait..."); + dev.RequestSense(out senseBuf, dev.Timeout, out duration); + fxSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf, out strSense); + } + while(fxSense.HasValue && fxSense.Value.ASC == 0x00 && (fxSense.Value.ASCQ == 0x1A || fxSense.Value.ASCQ != 0x04)); + + dev.RequestSense(out senseBuf, dev.Timeout, out duration); + fxSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf, out strSense); + + // And yet, did not rewind! + if(fxSense.HasValue && ((fxSense.Value.ASC == 0x00 && fxSense.Value.ASCQ != 0x04) || fxSense.Value.ASC != 0x00)) + { + DicConsole.WriteLine(); + DicConsole.ErrorWriteLine("Drive could not rewind, please correct. Sense follows..."); + DicConsole.ErrorWriteLine("{0}", strSense); + return; + } + + DicConsole.WriteLine(); + } + + // Check position + sense = dev.ReadPosition(out tapeBuf, out senseBuf, SscPositionForms.Short, dev.Timeout, out duration); + + if(sense) + { + // READ POSITION is mandatory starting SCSI-2, so do not cry if the drive does not recognize the command (SCSI-1 or earlier) + // Anyway, <=SCSI-1 tapes do not support partitions + fxSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf, out strSense); + if(fxSense.HasValue && ((fxSense.Value.ASC == 0x20 && fxSense.Value.ASCQ != 0x00) || fxSense.Value.ASC != 0x20)) + { + DicConsole.ErrorWriteLine("Could not get position. Sense follows..."); + DicConsole.ErrorWriteLine("{0}", strSense); + return; + } + } + else + { + // Not in partition 0 + if(tapeBuf[1] != 0) + { + DicConsole.Write("Drive not in partition 0. Rewinding, please wait..."); + // Rewind, let timeout apply + sense = dev.Locate(out senseBuf, false, 0, 0, dev.Timeout, out duration); + if(sense) + { + DicConsole.WriteLine(); + DicConsole.ErrorWriteLine("Drive could not rewind, please correct. Sense follows..."); + DicConsole.ErrorWriteLine("{0}", strSense); + return; + } + + // Still rewinding? + // TODO: Pause? + do + { + System.Threading.Thread.Sleep(1000); + DicConsole.Write("\rRewinding, please wait..."); + dev.RequestSense(out senseBuf, dev.Timeout, out duration); + fxSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf, out strSense); + } + while(fxSense.HasValue && fxSense.Value.ASC == 0x00 && (fxSense.Value.ASCQ == 0x1A || fxSense.Value.ASCQ == 0x19)); + + // And yet, did not rewind! + if(fxSense.HasValue && ((fxSense.Value.ASC == 0x00 && fxSense.Value.ASCQ != 0x04) || fxSense.Value.ASC != 0x00)) + { + DicConsole.WriteLine(); + DicConsole.ErrorWriteLine("Drive could not rewind, please correct. Sense follows..."); + DicConsole.ErrorWriteLine("{0}", strSense); + return; + } + + sense = dev.ReadPosition(out tapeBuf, out senseBuf, SscPositionForms.Short, dev.Timeout, out duration); + if(sense) + { + fxSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf, out strSense); + DicConsole.ErrorWriteLine("Drive could not rewind, please correct. Sense follows..."); + DicConsole.ErrorWriteLine("{0}", strSense); + return; + } + + // Still not in partition 0!!!? + if(tapeBuf[1] != 0) + { + DicConsole.ErrorWriteLine("Drive could not rewind to partition 0 but no error occurred..."); + return; + } + + DicConsole.WriteLine(); + } + } + + sidecar.BlockMedia = new BlockMediaType[1]; + sidecar.BlockMedia[0] = new BlockMediaType(); + sidecar.BlockMedia[0].SCSI = new SCSIType(); + byte scsiMediumTypeTape = 0; + byte scsiDensityCodeTape = 0; + + sense = dev.ModeSense10(out cmdBuf, out senseBuf, false, true, ScsiModeSensePageControl.Current, 0x3F, 0xFF, 5, out duration); + if(!sense || dev.Error) + { + sense = dev.ModeSense10(out cmdBuf, out senseBuf, false, true, ScsiModeSensePageControl.Current, 0x3F, 0x00, 5, out duration); + } + + Decoders.SCSI.Modes.DecodedMode? decMode = null; + + if(!sense && !dev.Error) + { + if(Decoders.SCSI.Modes.DecodeMode10(cmdBuf, dev.SCSIType).HasValue) + { + decMode = Decoders.SCSI.Modes.DecodeMode10(cmdBuf, dev.SCSIType); + sidecar.BlockMedia[0].SCSI.ModeSense10 = new DumpType(); + sidecar.BlockMedia[0].SCSI.ModeSense10.Image = outputPrefix + ".modesense10.bin"; + sidecar.BlockMedia[0].SCSI.ModeSense10.Size = cmdBuf.Length; + sidecar.BlockMedia[0].SCSI.ModeSense10.Checksums = Checksum.GetChecksums(cmdBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.BlockMedia[0].SCSI.ModeSense10.Image, cmdBuf); + } + } + + sense = dev.ModeSense6(out cmdBuf, out senseBuf, false, ScsiModeSensePageControl.Current, 0x3F, 0x00, 5, out duration); + if(sense || dev.Error) + sense = dev.ModeSense6(out cmdBuf, out senseBuf, false, ScsiModeSensePageControl.Current, 0x3F, 0x00, 5, out duration); + if(sense || dev.Error) + sense = dev.ModeSense(out cmdBuf, out senseBuf, 5, out duration); + + if(!sense && !dev.Error) + { + if(Decoders.SCSI.Modes.DecodeMode6(cmdBuf, dev.SCSIType).HasValue) + { + decMode = Decoders.SCSI.Modes.DecodeMode6(cmdBuf, dev.SCSIType); + sidecar.BlockMedia[0].SCSI.ModeSense = new DumpType(); + sidecar.BlockMedia[0].SCSI.ModeSense.Image = outputPrefix + ".modesense.bin"; + sidecar.BlockMedia[0].SCSI.ModeSense.Size = cmdBuf.Length; + sidecar.BlockMedia[0].SCSI.ModeSense.Checksums = Checksum.GetChecksums(cmdBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.BlockMedia[0].SCSI.ModeSense.Image, cmdBuf); + } + } + + // TODO: Check partitions page + if(decMode.HasValue) + { + scsiMediumTypeTape = (byte)decMode.Value.Header.MediumType; + if(decMode.Value.Header.BlockDescriptors != null && decMode.Value.Header.BlockDescriptors.Length >= 1) + scsiDensityCodeTape = (byte)decMode.Value.Header.BlockDescriptors[0].Density; + } + + if(dskType == MediaType.Unknown) + dskType = MediaTypeFromSCSI.Get((byte)dev.SCSIType, dev.Manufacturer, dev.Model, scsiMediumTypeTape, scsiDensityCodeTape, blocks, blockSize); + + DicConsole.WriteLine("Media identified as {0}", dskType); + + bool endOfMedia = false; + ulong currentBlock = 0; + ulong currentFile = 0; + byte currentPartition = 0; + byte totalPartitions = 1; // TODO: Handle partitions. + blockSize = 1; + ulong currentSize = 0; + ulong currentPartitionSize = 0; + ulong currentFileSize = 0; + + Checksum partitionChk; + Checksum fileChk; + List partitions = new List(); + List files = new List(); + TapeFileType currentTapeFile = new TapeFileType(); + TapePartitionType currentTapePartition = new TapePartitionType(); + + DicConsole.WriteLine(); + dumpFile = new DataFile(outputPrefix + ".bin"); + dataChk = new Checksum(); + start = DateTime.UtcNow; + mhddLog = new MHDDLog(outputPrefix + ".mhddlog.bin", dev, blocks, blockSize, 1); + ibgLog = new IBGLog(outputPrefix + ".ibg", 0x0008); + + currentTapeFile = new TapeFileType(); + currentTapeFile.Image = new ImageType(); + currentTapeFile.Image.format = "BINARY"; + currentTapeFile.Image.offset = (long)currentSize; + currentTapeFile.Image.offsetSpecified = true; + currentTapeFile.Image.Value = outputPrefix + ".bin"; + currentTapeFile.Sequence = (long)currentFile; + currentTapeFile.StartBlock = (long)currentBlock; + fileChk = new Checksum(); + currentTapePartition = new TapePartitionType(); + currentTapePartition.Image = new ImageType(); + currentTapePartition.Image.format = "BINARY"; + currentTapePartition.Image.offset = (long)currentSize; + currentTapePartition.Image.offsetSpecified = true; + currentTapePartition.Image.Value = outputPrefix + ".bin"; + currentTapePartition.Sequence = (long)currentPartition; + currentTapePartition.StartBlock = (long)currentBlock; + partitionChk = new Checksum(); + + aborted = false; + System.Console.CancelKeyPress += (sender, e) => + { + e.Cancel = aborted = true; + }; + + while(currentPartition < totalPartitions) + { + if(aborted) + break; + + if(endOfMedia) + { + DicConsole.WriteLine(); + DicConsole.WriteLine("Finished partition {0}", currentPartition); + currentTapePartition.File = files.ToArray(); + currentTapePartition.Checksums = partitionChk.End().ToArray(); + currentTapePartition.EndBlock = (long)(currentBlock - 1); + currentTapePartition.Size = (long)currentPartitionSize; + partitions.Add(currentTapePartition); + + currentPartition++; + + if(currentPartition < totalPartitions) + { + currentFile++; + currentTapeFile = new TapeFileType(); + currentTapeFile.Image = new ImageType(); + currentTapeFile.Image.format = "BINARY"; + currentTapeFile.Image.offset = (long)currentSize; + currentTapeFile.Image.offsetSpecified = true; + currentTapeFile.Image.Value = outputPrefix + ".bin"; + currentTapeFile.Sequence = (long)currentFile; + currentTapeFile.StartBlock = (long)currentBlock; + currentFileSize = 0; + fileChk = new Checksum(); + files = new List(); + currentTapePartition = new TapePartitionType(); + currentTapePartition.Image = new ImageType(); + currentTapePartition.Image.format = "BINARY"; + currentTapePartition.Image.offset = (long)currentSize; + currentTapePartition.Image.offsetSpecified = true; + currentTapePartition.Image.Value = outputPrefix + ".bin"; + currentTapePartition.Sequence = currentPartition; + currentTapePartition.StartBlock = (long)currentBlock; + currentPartitionSize = 0; + partitionChk = new Checksum(); + DicConsole.WriteLine("Seeking to partition {0}", currentPartition); + sense = dev.Locate(out senseBuf, false, currentPartition, 0, dev.Timeout, out duration); + totalDuration += duration; + } + + continue; + } + +#pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator + if(currentSpeed > maxSpeed && currentSpeed != 0) + maxSpeed = currentSpeed; + if(currentSpeed < minSpeed && currentSpeed != 0) + minSpeed = currentSpeed; +#pragma warning restore RECS0018 // Comparison of floating point numbers with equality operator + + DicConsole.Write("\rReading block {0} ({1:F3} MiB/sec.)", currentBlock, currentSpeed); + + sense = dev.Read6(out tapeBuf, out senseBuf, false, blockSize, blockSize, dev.Timeout, out duration); + totalDuration += duration; + + if(sense) + { + fxSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf, out strSense); + if(fxSense.Value.ASC == 0x00 && fxSense.Value.ASCQ == 0x00 && fxSense.Value.ILI && fxSense.Value.InformationValid) + { + blockSize = (uint)((int)blockSize - BitConverter.ToInt32(BitConverter.GetBytes(fxSense.Value.Information), 0)); + + DicConsole.WriteLine(); + DicConsole.WriteLine("Blocksize changed to {0} bytes at block {1}", blockSize, currentBlock); + + sense = dev.Space(out senseBuf, SscSpaceCodes.LogicalBlock, -1, dev.Timeout, out duration); + totalDuration += duration; + + if(sense) + { + fxSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf, out strSense); + DicConsole.WriteLine(); + DicConsole.ErrorWriteLine("Drive could not go back one block. Sense follows..."); + DicConsole.ErrorWriteLine("{0}", strSense); + dumpFile.Close(); + return; + } + + continue; + } + + if(fxSense.Value.SenseKey == Decoders.SCSI.SenseKeys.BlankCheck) + { + if(currentBlock == 0) + { + DicConsole.WriteLine(); + DicConsole.ErrorWriteLine("Cannot dump a blank tape..."); + dumpFile.Close(); + return; + } + + // For sure this is an end-of-tape/partition + if(fxSense.Value.ASC == 0x00 && (fxSense.Value.ASCQ == 0x02 || fxSense.Value.ASCQ == 0x05)) + { + // TODO: Detect end of partition + endOfMedia = true; + continue; + } + + DicConsole.WriteLine(); + DicConsole.WriteLine("Blank block found, end of tape?"); + endOfMedia = true; + continue; + } + + if((fxSense.Value.SenseKey == Decoders.SCSI.SenseKeys.NoSense || fxSense.Value.SenseKey == Decoders.SCSI.SenseKeys.RecoveredError) && + (fxSense.Value.ASCQ == 0x02 || fxSense.Value.ASCQ == 0x05)) + { + // TODO: Detect end of partition + endOfMedia = true; + continue; + } + + if((fxSense.Value.SenseKey == Decoders.SCSI.SenseKeys.NoSense || fxSense.Value.SenseKey == Decoders.SCSI.SenseKeys.RecoveredError) && + fxSense.Value.ASCQ == 0x01) + { + currentTapeFile.Checksums = fileChk.End().ToArray(); + currentTapeFile.EndBlock = (long)(currentBlock - 1); + currentTapeFile.Size = (long)currentFileSize; + files.Add(currentTapeFile); + + currentFile++; + currentTapeFile = new TapeFileType(); + currentTapeFile.Image = new ImageType(); + currentTapeFile.Image.format = "BINARY"; + currentTapeFile.Image.offset = (long)currentSize; + currentTapeFile.Image.offsetSpecified = true; + currentTapeFile.Image.Value = outputPrefix + ".bin"; + currentTapeFile.Sequence = (long)currentFile; + currentTapeFile.StartBlock = (long)currentBlock; + currentFileSize = 0; + fileChk = new Checksum(); + + DicConsole.WriteLine(); + DicConsole.WriteLine("Changed to file {0} at block {1}", currentFile, currentBlock); + continue; + } + + // TODO: Add error recovering for tapes + fxSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf, out strSense); + DicConsole.ErrorWriteLine("Drive could not read block. Sense follows..."); + DicConsole.ErrorWriteLine("{0}", strSense); + return; + } + + mhddLog.Write(currentBlock, duration); + ibgLog.Write(currentBlock, currentSpeed * 1024); + dumpFile.Write(tapeBuf); + + DateTime chkStart = DateTime.UtcNow; + dataChk.Update(tapeBuf); + fileChk.Update(tapeBuf); + partitionChk.Update(tapeBuf); + DateTime chkEnd = DateTime.UtcNow; + double chkDuration = (chkEnd - chkStart).TotalMilliseconds; + totalChkDuration += chkDuration; + + if(currentBlock % 10 == 0) + currentSpeed = ((double)2448 / (double)1048576) / (duration / (double)1000); + currentBlock++; + currentSize += blockSize; + currentFileSize += blockSize; + currentPartitionSize += blockSize; + } + + blocks = currentBlock + 1; + DicConsole.WriteLine(); + end = DateTime.UtcNow; + mhddLog.Close(); + ibgLog.Close(dev, blocks, blockSize, (end - start).TotalSeconds, currentSpeed * 1024, (((double)blockSize * (double)(blocks + 1)) / 1024) / (totalDuration / 1000), devicePath); + + DicConsole.WriteLine("Took a total of {0:F3} seconds ({1:F3} processing commands, {2:F3} checksumming).", (end - start).TotalSeconds, totalDuration / 1000, totalChkDuration / 1000); +#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created + DicConsole.WriteLine("Avegare speed: {0:F3} MiB/sec.", (((double)blockSize * (double)(blocks + 1)) / 1048576) / (totalDuration / 1000)); +#pragma warning restore IDE0004 // Cast is necessary, otherwise incorrect value is created + DicConsole.WriteLine("Fastest speed burst: {0:F3} MiB/sec.", maxSpeed); + DicConsole.WriteLine("Slowest speed burst: {0:F3} MiB/sec.", minSpeed); + + sidecar.BlockMedia[0].Checksums = dataChk.End().ToArray(); + sidecar.BlockMedia[0].Dimensions = Metadata.Dimensions.DimensionsFromMediaType(dskType); + string xmlDskTyp, xmlDskSubTyp; + Metadata.MediaType.MediaTypeToString(dskType, out xmlDskTyp, out xmlDskSubTyp); + sidecar.BlockMedia[0].DiskType = xmlDskTyp; + sidecar.BlockMedia[0].DiskSubType = xmlDskSubTyp; + // TODO: Implement device firmware revision + sidecar.BlockMedia[0].Image = new ImageType(); + sidecar.BlockMedia[0].Image.format = "Raw disk image (sector by sector copy)"; + sidecar.BlockMedia[0].Image.Value = outputPrefix + ".bin"; + sidecar.BlockMedia[0].LogicalBlocks = (long)blocks; + sidecar.BlockMedia[0].Size = (long)(currentSize); + sidecar.BlockMedia[0].DumpHardwareArray = new DumpHardwareType[1]; + sidecar.BlockMedia[0].DumpHardwareArray[0] = new DumpHardwareType(); + sidecar.BlockMedia[0].DumpHardwareArray[0].Extents = new ExtentType[1]; + sidecar.BlockMedia[0].DumpHardwareArray[0].Extents[0] = new ExtentType(); + sidecar.BlockMedia[0].DumpHardwareArray[0].Extents[0].Start = 0; + sidecar.BlockMedia[0].DumpHardwareArray[0].Extents[0].End = (int)(blocks - 1); + sidecar.BlockMedia[0].DumpHardwareArray[0].Manufacturer = dev.Manufacturer; + sidecar.BlockMedia[0].DumpHardwareArray[0].Model = dev.Model; + sidecar.BlockMedia[0].DumpHardwareArray[0].Revision = dev.Revision; + sidecar.BlockMedia[0].DumpHardwareArray[0].Serial = dev.Serial; + sidecar.BlockMedia[0].DumpHardwareArray[0].Software = new SoftwareType(); + sidecar.BlockMedia[0].DumpHardwareArray[0].Software.Name = "DiscImageChef"; + sidecar.BlockMedia[0].DumpHardwareArray[0].Software.OperatingSystem = dev.PlatformID.ToString(); + sidecar.BlockMedia[0].DumpHardwareArray[0].Software.Version = typeof(SCSI).Assembly.GetName().Version.ToString(); + sidecar.BlockMedia[0].TapeInformation = partitions.ToArray(); + + if(!aborted) + { + DicConsole.WriteLine("Writing metadata sidecar"); + + FileStream xmlFs = new FileStream(outputPrefix + ".cicm.xml", + FileMode.Create); + + System.Xml.Serialization.XmlSerializer xmlSer = new System.Xml.Serialization.XmlSerializer(typeof(CICMMetadataType)); + xmlSer.Serialize(xmlFs, sidecar); + xmlFs.Close(); + } + + Statistics.AddMedia(dskType, true); + + return; + } + + if(blocks == 0) + { + DicConsole.ErrorWriteLine("Unable to read medium or empty medium present..."); + return; + } + + bool compactDisc = true; + Decoders.CD.FullTOC.CDFullTOC? toc = null; + byte scsiMediumType = 0; + byte scsiDensityCode = 0; + bool containsFloppyPage = false; + ushort currentProfile = 0x0001; + bool isXbox = false; + + #region MultiMediaDevice + if(dev.SCSIType == Decoders.SCSI.PeripheralDeviceTypes.MultiMediaDevice) + { + sidecar.OpticalDisc = new OpticalDiscType[1]; + sidecar.OpticalDisc[0] = new OpticalDiscType(); + opticalDisc = true; + + sense = dev.GetConfiguration(out cmdBuf, out senseBuf, 0, MmcGetConfigurationRt.Current, dev.Timeout, out duration); + if(!sense) + { + Decoders.SCSI.MMC.Features.SeparatedFeatures ftr = Decoders.SCSI.MMC.Features.Separate(cmdBuf); + currentProfile = ftr.CurrentProfile; + + switch(ftr.CurrentProfile) + { + case 0x0001: + dskType = MediaType.GENERIC_HDD; + goto default; + case 0x0005: + dskType = MediaType.CDMO; + break; + case 0x0008: + dskType = MediaType.CD; + break; + case 0x0009: + dskType = MediaType.CDR; + break; + case 0x000A: + dskType = MediaType.CDRW; + break; + case 0x0010: + dskType = MediaType.DVDROM; + goto default; + case 0x0011: + dskType = MediaType.DVDR; + goto default; + case 0x0012: + dskType = MediaType.DVDRAM; + goto default; + case 0x0013: + case 0x0014: + dskType = MediaType.DVDRW; + goto default; + case 0x0015: + case 0x0016: + dskType = MediaType.DVDRDL; + goto default; + case 0x0017: + dskType = MediaType.DVDRWDL; + goto default; + case 0x0018: + dskType = MediaType.DVDDownload; + goto default; + case 0x001A: + dskType = MediaType.DVDPRW; + goto default; + case 0x001B: + dskType = MediaType.DVDPR; + goto default; + case 0x0020: + dskType = MediaType.DDCD; + goto default; + case 0x0021: + dskType = MediaType.DDCDR; + goto default; + case 0x0022: + dskType = MediaType.DDCDRW; + goto default; + case 0x002A: + dskType = MediaType.DVDPRWDL; + goto default; + case 0x002B: + dskType = MediaType.DVDPRDL; + goto default; + case 0x0040: + dskType = MediaType.BDROM; + goto default; + case 0x0041: + case 0x0042: + dskType = MediaType.BDR; + goto default; + case 0x0043: + dskType = MediaType.BDRE; + goto default; + case 0x0050: + dskType = MediaType.HDDVDROM; + goto default; + case 0x0051: + dskType = MediaType.HDDVDR; + goto default; + case 0x0052: + dskType = MediaType.HDDVDRAM; + goto default; + case 0x0053: + dskType = MediaType.HDDVDRW; + goto default; + case 0x0058: + dskType = MediaType.HDDVDRDL; + goto default; + case 0x005A: + dskType = MediaType.HDDVDRWDL; + goto default; + default: + compactDisc = false; + break; + } + } + + #region CompactDisc + if(compactDisc) + { + // We discarded all discs that falsify a TOC before requesting a real TOC + // No TOC, no CD (or an empty one) + bool tocSense = dev.ReadRawToc(out cmdBuf, out senseBuf, 1, dev.Timeout, out duration); + if(!tocSense) + { + toc = Decoders.CD.FullTOC.Decode(cmdBuf); + if(toc.HasValue) + { + tmpBuf = new byte[cmdBuf.Length - 2]; + Array.Copy(cmdBuf, 2, tmpBuf, 0, cmdBuf.Length - 2); + sidecar.OpticalDisc[0].TOC = new DumpType(); + sidecar.OpticalDisc[0].TOC.Image = outputPrefix + ".toc.bin"; + sidecar.OpticalDisc[0].TOC.Size = tmpBuf.Length; + sidecar.OpticalDisc[0].TOC.Checksums = Checksum.GetChecksums(tmpBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].TOC.Image, tmpBuf); + + // ATIP exists on blank CDs + sense = dev.ReadAtip(out cmdBuf, out senseBuf, dev.Timeout, out duration); + if(!sense) + { + Decoders.CD.ATIP.CDATIP? atip = Decoders.CD.ATIP.Decode(cmdBuf); + if(atip.HasValue) + { + if(blocks == 0) + { + DicConsole.ErrorWriteLine("Cannot dump blank media."); + return; + } + + // Only CD-R and CD-RW have ATIP + dskType = atip.Value.DiscType ? MediaType.CDRW : MediaType.CDR; + + tmpBuf = new byte[cmdBuf.Length - 4]; + Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); + sidecar.OpticalDisc[0].ATIP = new DumpType(); + sidecar.OpticalDisc[0].ATIP.Image = outputPrefix + ".atip.bin"; + sidecar.OpticalDisc[0].ATIP.Size = tmpBuf.Length; + sidecar.OpticalDisc[0].ATIP.Checksums = Checksum.GetChecksums(tmpBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].TOC.Image, tmpBuf); + } + } + + sense = dev.ReadDiscInformation(out cmdBuf, out senseBuf, MmcDiscInformationDataTypes.DiscInformation, dev.Timeout, out duration); + if(!sense) + { + Decoders.SCSI.MMC.DiscInformation.StandardDiscInformation? discInfo = Decoders.SCSI.MMC.DiscInformation.Decode000b(cmdBuf); + if(discInfo.HasValue) + { + // If it is a read-only CD, check CD type if available + if(dskType == MediaType.CD) + { + switch(discInfo.Value.DiscType) + { + case 0x10: + dskType = MediaType.CDI; + break; + case 0x20: + dskType = MediaType.CDROMXA; + break; + } + } + } + } + + int sessions = 1; + int firstTrackLastSession = 0; + + sense = dev.ReadSessionInfo(out cmdBuf, out senseBuf, dev.Timeout, out duration); + if(!sense) + { + Decoders.CD.Session.CDSessionInfo? session = Decoders.CD.Session.Decode(cmdBuf); + if(session.HasValue) + { + sessions = session.Value.LastCompleteSession; + firstTrackLastSession = session.Value.TrackDescriptors[0].TrackNumber; + } + } + + if(dskType == MediaType.CD) + { + bool hasDataTrack = false; + bool hasAudioTrack = false; + bool allFirstSessionTracksAreAudio = true; + bool hasVideoTrack = false; + + if(toc.HasValue) + { + foreach(Decoders.CD.FullTOC.TrackDataDescriptor track in toc.Value.TrackDescriptors) + { + if(track.TNO == 1 && + ((Decoders.CD.TOC_CONTROL)(track.CONTROL & 0x0D) == Decoders.CD.TOC_CONTROL.DataTrack || + (Decoders.CD.TOC_CONTROL)(track.CONTROL & 0x0D) == Decoders.CD.TOC_CONTROL.DataTrackIncremental)) + { + allFirstSessionTracksAreAudio &= firstTrackLastSession != 1; + } + + if((Decoders.CD.TOC_CONTROL)(track.CONTROL & 0x0D) == Decoders.CD.TOC_CONTROL.DataTrack || + (Decoders.CD.TOC_CONTROL)(track.CONTROL & 0x0D) == Decoders.CD.TOC_CONTROL.DataTrackIncremental) + { + hasDataTrack = true; + allFirstSessionTracksAreAudio &= track.TNO >= firstTrackLastSession; + } + else + hasAudioTrack = true; + + hasVideoTrack |= track.ADR == 4; + } + } + + if(hasDataTrack && hasAudioTrack && allFirstSessionTracksAreAudio && sessions == 2) + dskType = MediaType.CDPLUS; + if(!hasDataTrack && hasAudioTrack && sessions == 1) + dskType = MediaType.CDDA; + if(hasDataTrack && !hasAudioTrack && sessions == 1) + dskType = MediaType.CDROM; + if(hasVideoTrack && !hasDataTrack && sessions == 1) + dskType = MediaType.CDV; + } + + sense = dev.ReadPma(out cmdBuf, out senseBuf, dev.Timeout, out duration); + if(!sense) + { + if(Decoders.CD.PMA.Decode(cmdBuf).HasValue) + { + tmpBuf = new byte[cmdBuf.Length - 4]; + Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); + sidecar.OpticalDisc[0].PMA = new DumpType(); + sidecar.OpticalDisc[0].PMA.Image = outputPrefix + ".pma.bin"; + sidecar.OpticalDisc[0].PMA.Size = tmpBuf.Length; + sidecar.OpticalDisc[0].PMA.Checksums = Checksum.GetChecksums(tmpBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].PMA.Image, tmpBuf); + } + } + + sense = dev.ReadCdText(out cmdBuf, out senseBuf, dev.Timeout, out duration); + if(!sense) + { + if(Decoders.CD.CDTextOnLeadIn.Decode(cmdBuf).HasValue) + { + tmpBuf = new byte[cmdBuf.Length - 4]; + Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); + sidecar.OpticalDisc[0].LeadInCdText = new DumpType(); + sidecar.OpticalDisc[0].LeadInCdText.Image = outputPrefix + ".cdtext.bin"; + sidecar.OpticalDisc[0].LeadInCdText.Size = tmpBuf.Length; + sidecar.OpticalDisc[0].LeadInCdText.Checksums = Checksum.GetChecksums(tmpBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].LeadInCdText.Image, tmpBuf); + } + } + } + } + + physicalBlockSize = 2448; + } + #endregion CompactDisc + else + { + #region Nintendo + if(dskType == MediaType.Unknown && blocks > 0) + { + sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.PhysicalInformation, 0, dev.Timeout, out duration); + if(!sense) + { + Decoders.DVD.PFI.PhysicalFormatInformation? nintendoPfi = Decoders.DVD.PFI.Decode(cmdBuf); + if(nintendoPfi != null) + { + if(nintendoPfi.Value.DiskCategory == Decoders.DVD.DiskCategory.Nintendo && + nintendoPfi.Value.PartVersion == 15) + { + throw new NotImplementedException("Dumping Nintendo GameCube or Wii discs is not yet implemented."); + } + } + } + } + #endregion Nintendo + + #region All DVD and HD DVD types + if(dskType == MediaType.DVDDownload || dskType == MediaType.DVDPR || + dskType == MediaType.DVDPRDL || dskType == MediaType.DVDPRW || + dskType == MediaType.DVDPRWDL || dskType == MediaType.DVDR || + dskType == MediaType.DVDRAM || dskType == MediaType.DVDRDL || + dskType == MediaType.DVDROM || dskType == MediaType.DVDRW || + dskType == MediaType.DVDRWDL || dskType == MediaType.HDDVDR || + dskType == MediaType.HDDVDRAM || dskType == MediaType.HDDVDRDL || + dskType == MediaType.HDDVDROM || dskType == MediaType.HDDVDRW || + dskType == MediaType.HDDVDRWDL) + { + + sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.PhysicalInformation, 0, dev.Timeout, out duration); + if(!sense) + { + if(Decoders.DVD.PFI.Decode(cmdBuf).HasValue) + { + tmpBuf = new byte[cmdBuf.Length - 4]; + Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); + sidecar.OpticalDisc[0].PFI = new DumpType(); + sidecar.OpticalDisc[0].PFI.Image = outputPrefix + ".pfi.bin"; + sidecar.OpticalDisc[0].PFI.Size = tmpBuf.Length; + sidecar.OpticalDisc[0].PFI.Checksums = Checksum.GetChecksums(tmpBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].PFI.Image, tmpBuf); + + Decoders.DVD.PFI.PhysicalFormatInformation decPfi = Decoders.DVD.PFI.Decode(cmdBuf).Value; + DicConsole.WriteLine("PFI:\n{0}", Decoders.DVD.PFI.Prettify(decPfi)); + + // False book types + if(dskType == MediaType.DVDROM) + { + switch(decPfi.DiskCategory) + { + case Decoders.DVD.DiskCategory.DVDPR: + dskType = MediaType.DVDPR; + break; + case Decoders.DVD.DiskCategory.DVDPRDL: + dskType = MediaType.DVDPRDL; + break; + case Decoders.DVD.DiskCategory.DVDPRW: + dskType = MediaType.DVDPRW; + break; + case Decoders.DVD.DiskCategory.DVDPRWDL: + dskType = MediaType.DVDPRWDL; + break; + case Decoders.DVD.DiskCategory.DVDR: + if(decPfi.PartVersion == 6) + dskType = MediaType.DVDRDL; + else + dskType = MediaType.DVDR; + break; + case Decoders.DVD.DiskCategory.DVDRAM: + dskType = MediaType.DVDRAM; + break; + default: + dskType = MediaType.DVDROM; + break; + case Decoders.DVD.DiskCategory.DVDRW: + if(decPfi.PartVersion == 3) + dskType = MediaType.DVDRWDL; + else + dskType = MediaType.DVDRW; + break; + case Decoders.DVD.DiskCategory.HDDVDR: + dskType = MediaType.HDDVDR; + break; + case Decoders.DVD.DiskCategory.HDDVDRAM: + dskType = MediaType.HDDVDRAM; + break; + case Decoders.DVD.DiskCategory.HDDVDROM: + dskType = MediaType.HDDVDROM; + break; + case Decoders.DVD.DiskCategory.HDDVDRW: + dskType = MediaType.HDDVDRW; + break; + case Decoders.DVD.DiskCategory.Nintendo: + if(decPfi.DiscSize == Decoders.DVD.DVDSize.Eighty) + dskType = MediaType.GOD; + else + dskType = MediaType.WOD; + break; + case Decoders.DVD.DiskCategory.UMD: + dskType = MediaType.UMD; + break; + } + } + } + } + sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.DiscManufacturingInformation, 0, dev.Timeout, out duration); + if(!sense) + { + if(Decoders.Xbox.DMI.IsXbox(cmdBuf) || Decoders.Xbox.DMI.IsXbox360(cmdBuf)) + { + if(Decoders.Xbox.DMI.IsXbox(cmdBuf)) + dskType = MediaType.XGD; + else if(Decoders.Xbox.DMI.IsXbox360(cmdBuf)) + { + dskType = MediaType.XGD2; + + // All XGD3 all have the same number of blocks + if(blocks == 25063 || // Locked (or non compatible drive) + blocks == 4229664 || // Xtreme unlock + blocks == 4246304) // Wxripper unlock + dskType = MediaType.XGD3; + } + + byte[] inqBuf; + sense = dev.ScsiInquiry(out inqBuf, out senseBuf); + + if(sense || !Decoders.SCSI.Inquiry.Decode(inqBuf).HasValue || + (Decoders.SCSI.Inquiry.Decode(inqBuf).HasValue && !Decoders.SCSI.Inquiry.Decode(inqBuf).Value.KreonPresent)) + throw new NotImplementedException("Dumping Xbox Game Discs requires a drive with Kreon firmware."); + + if(dumpRaw && !force) + { + DicConsole.ErrorWriteLine("Not continuing. If you want to continue reading cooked data when raw is not available use the force option."); + // TODO: Exit more gracefully + return; + } + + isXbox = true; + } + + if(cmdBuf.Length == 2052) + { + tmpBuf = new byte[cmdBuf.Length - 4]; + Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); + sidecar.OpticalDisc[0].DMI = new DumpType(); + sidecar.OpticalDisc[0].DMI.Image = outputPrefix + ".dmi.bin"; + sidecar.OpticalDisc[0].DMI.Size = tmpBuf.Length; + sidecar.OpticalDisc[0].DMI.Checksums = Checksum.GetChecksums(tmpBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].DMI.Image, tmpBuf); + } + } + } + #endregion All DVD and HD DVD types + + #region DVD-ROM + if(dskType == MediaType.DVDDownload || dskType == MediaType.DVDROM) + { + sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.CopyrightInformation, 0, dev.Timeout, out duration); + if(!sense) + { + if(Decoders.DVD.CSS_CPRM.DecodeLeadInCopyright(cmdBuf).HasValue) + { + tmpBuf = new byte[cmdBuf.Length - 4]; + Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); + sidecar.OpticalDisc[0].CMI = new DumpType(); + sidecar.OpticalDisc[0].CMI.Image = outputPrefix + ".cmi.bin"; + sidecar.OpticalDisc[0].CMI.Size = tmpBuf.Length; + sidecar.OpticalDisc[0].CMI.Checksums = Checksum.GetChecksums(tmpBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].CMI.Image, tmpBuf); + + Decoders.DVD.CSS_CPRM.LeadInCopyright cpy = Decoders.DVD.CSS_CPRM.DecodeLeadInCopyright(cmdBuf).Value; + if(cpy.CopyrightType != Decoders.DVD.CopyrightType.NoProtection) + sidecar.OpticalDisc[0].CopyProtection = cpy.CopyrightType.ToString(); + } + } + } + #endregion DVD-ROM + + #region DVD-ROM and HD DVD-ROM + if(dskType == MediaType.DVDDownload || dskType == MediaType.DVDROM || + dskType == MediaType.HDDVDROM) + { + sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.BurstCuttingArea, 0, dev.Timeout, out duration); + if(!sense) + { + tmpBuf = new byte[cmdBuf.Length - 4]; + Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); + sidecar.OpticalDisc[0].BCA = new DumpType(); + sidecar.OpticalDisc[0].BCA.Image = outputPrefix + ".bca.bin"; + sidecar.OpticalDisc[0].BCA.Size = tmpBuf.Length; + sidecar.OpticalDisc[0].BCA.Checksums = Checksum.GetChecksums(tmpBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].BCA.Image, tmpBuf); + } + } + #endregion DVD-ROM and HD DVD-ROM + + #region DVD-RAM and HD DVD-RAM + if(dskType == MediaType.DVDRAM || dskType == MediaType.HDDVDRAM) + { + sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.DVDRAM_DDS, 0, dev.Timeout, out duration); + if(!sense) + { + if(Decoders.DVD.DDS.Decode(cmdBuf).HasValue) + { + tmpBuf = new byte[cmdBuf.Length - 4]; + Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); + sidecar.OpticalDisc[0].DDS = new DumpType(); + sidecar.OpticalDisc[0].DDS.Image = outputPrefix + ".dds.bin"; + sidecar.OpticalDisc[0].DDS.Size = tmpBuf.Length; + sidecar.OpticalDisc[0].DDS.Checksums = Checksum.GetChecksums(tmpBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].DDS.Image, tmpBuf); + } + } + + sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.DVDRAM_SpareAreaInformation, 0, dev.Timeout, out duration); + if(!sense) + { + if(Decoders.DVD.Spare.Decode(cmdBuf).HasValue) + { + tmpBuf = new byte[cmdBuf.Length - 4]; + Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); + sidecar.OpticalDisc[0].SAI = new DumpType(); + sidecar.OpticalDisc[0].SAI.Image = outputPrefix + ".sai.bin"; + sidecar.OpticalDisc[0].SAI.Size = tmpBuf.Length; + sidecar.OpticalDisc[0].SAI.Checksums = Checksum.GetChecksums(tmpBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].SAI.Image, tmpBuf); + } + } + } + #endregion DVD-RAM and HD DVD-RAM + + #region DVD-R and DVD-RW + if(dskType == MediaType.DVDR || dskType == MediaType.DVDRW) + { + sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.PreRecordedInfo, 0, dev.Timeout, out duration); + if(!sense) + { + tmpBuf = new byte[cmdBuf.Length - 4]; + Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); + sidecar.OpticalDisc[0].PRI = new DumpType(); + sidecar.OpticalDisc[0].PRI.Image = outputPrefix + ".pri.bin"; + sidecar.OpticalDisc[0].PRI.Size = tmpBuf.Length; + sidecar.OpticalDisc[0].PRI.Checksums = Checksum.GetChecksums(tmpBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].SAI.Image, tmpBuf); + } + } + #endregion DVD-R and DVD-RW + + #region DVD-R, DVD-RW and HD DVD-R + if(dskType == MediaType.DVDR || dskType == MediaType.DVDRW || dskType == MediaType.HDDVDR) + { + sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.DVDR_MediaIdentifier, 0, dev.Timeout, out duration); + if(!sense) + { + tmpBuf = new byte[cmdBuf.Length - 4]; + Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); + sidecar.OpticalDisc[0].MediaID = new DumpType(); + sidecar.OpticalDisc[0].MediaID.Image = outputPrefix + ".mid.bin"; + sidecar.OpticalDisc[0].MediaID.Size = tmpBuf.Length; + sidecar.OpticalDisc[0].MediaID.Checksums = Checksum.GetChecksums(tmpBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].MediaID.Image, tmpBuf); + } + + sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.DVDR_PhysicalInformation, 0, dev.Timeout, out duration); + if(!sense) + { + tmpBuf = new byte[cmdBuf.Length - 4]; + Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); + sidecar.OpticalDisc[0].PFIR = new DumpType(); + sidecar.OpticalDisc[0].PFIR.Image = outputPrefix + ".pfir.bin"; + sidecar.OpticalDisc[0].PFIR.Size = tmpBuf.Length; + sidecar.OpticalDisc[0].PFIR.Checksums = Checksum.GetChecksums(tmpBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].PFIR.Image, tmpBuf); + } + } + #endregion DVD-R, DVD-RW and HD DVD-R + + #region All DVD+ + if(dskType == MediaType.DVDPR || dskType == MediaType.DVDPRDL || + dskType == MediaType.DVDPRW || dskType == MediaType.DVDPRWDL) + { + sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.ADIP, 0, dev.Timeout, out duration); + if(!sense) + { + tmpBuf = new byte[cmdBuf.Length - 4]; + Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); + sidecar.OpticalDisc[0].ADIP = new DumpType(); + sidecar.OpticalDisc[0].ADIP.Image = outputPrefix + ".adip.bin"; + sidecar.OpticalDisc[0].ADIP.Size = tmpBuf.Length; + sidecar.OpticalDisc[0].ADIP.Checksums = Checksum.GetChecksums(tmpBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].ADIP.Image, tmpBuf); + } + + sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.DCB, 0, dev.Timeout, out duration); + if(!sense) + { + tmpBuf = new byte[cmdBuf.Length - 4]; + Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); + sidecar.OpticalDisc[0].DCB = new DumpType(); + sidecar.OpticalDisc[0].DCB.Image = outputPrefix + ".dcb.bin"; + sidecar.OpticalDisc[0].DCB.Size = tmpBuf.Length; + sidecar.OpticalDisc[0].DCB.Checksums = Checksum.GetChecksums(tmpBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].DCB.Image, tmpBuf); + } + } + #endregion All DVD+ + + #region HD DVD-ROM + if(dskType == MediaType.HDDVDROM) + { + sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.HDDVD_CopyrightInformation, 0, dev.Timeout, out duration); + if(!sense) + { + tmpBuf = new byte[cmdBuf.Length - 4]; + Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); + sidecar.OpticalDisc[0].CMI = new DumpType(); + sidecar.OpticalDisc[0].CMI.Image = outputPrefix + ".cmi.bin"; + sidecar.OpticalDisc[0].CMI.Size = tmpBuf.Length; + sidecar.OpticalDisc[0].CMI.Checksums = Checksum.GetChecksums(tmpBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].CMI.Image, tmpBuf); + } + } + #endregion HD DVD-ROM + + #region All Blu-ray + if(dskType == MediaType.BDR || dskType == MediaType.BDRE || dskType == MediaType.BDROM || + dskType == MediaType.BDRXL || dskType == MediaType.BDREXL) + { + sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.BD, 0, 0, MmcDiscStructureFormat.DiscInformation, 0, dev.Timeout, out duration); + if(!sense) + { + if(Decoders.Bluray.DI.Decode(cmdBuf).HasValue) + { + tmpBuf = new byte[cmdBuf.Length - 4]; + Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); + sidecar.OpticalDisc[0].DI = new DumpType(); + sidecar.OpticalDisc[0].DI.Image = outputPrefix + ".di.bin"; + sidecar.OpticalDisc[0].DI.Size = tmpBuf.Length; + sidecar.OpticalDisc[0].DI.Checksums = Checksum.GetChecksums(tmpBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].DI.Image, tmpBuf); + } + } + + sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.BD, 0, 0, MmcDiscStructureFormat.PAC, 0, dev.Timeout, out duration); + if(!sense) + { + tmpBuf = new byte[cmdBuf.Length - 4]; + Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); + sidecar.OpticalDisc[0].PAC = new DumpType(); + sidecar.OpticalDisc[0].PAC.Image = outputPrefix + ".pac.bin"; + sidecar.OpticalDisc[0].PAC.Size = tmpBuf.Length; + sidecar.OpticalDisc[0].PAC.Checksums = Checksum.GetChecksums(tmpBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].PAC.Image, tmpBuf); + } + } + #endregion All Blu-ray + + + #region BD-ROM only + if(dskType == MediaType.BDROM) + { + sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.BD, 0, 0, MmcDiscStructureFormat.BD_BurstCuttingArea, 0, dev.Timeout, out duration); + if(!sense) + { + tmpBuf = new byte[cmdBuf.Length - 4]; + Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); + sidecar.OpticalDisc[0].BCA = new DumpType(); + sidecar.OpticalDisc[0].BCA.Image = outputPrefix + ".bca.bin"; + sidecar.OpticalDisc[0].BCA.Size = tmpBuf.Length; + sidecar.OpticalDisc[0].BCA.Checksums = Checksum.GetChecksums(tmpBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].BCA.Image, tmpBuf); + } + } + #endregion BD-ROM only + + #region Writable Blu-ray only + if(dskType == MediaType.BDR || dskType == MediaType.BDRE || + dskType == MediaType.BDRXL || dskType == MediaType.BDREXL) + { + sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.BD, 0, 0, MmcDiscStructureFormat.BD_DDS, 0, dev.Timeout, out duration); + if(!sense) + { + tmpBuf = new byte[cmdBuf.Length - 4]; + Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); + sidecar.OpticalDisc[0].DDS = new DumpType(); + sidecar.OpticalDisc[0].DDS.Image = outputPrefix + ".dds.bin"; + sidecar.OpticalDisc[0].DDS.Size = tmpBuf.Length; + sidecar.OpticalDisc[0].DDS.Checksums = Checksum.GetChecksums(tmpBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].DDS.Image, tmpBuf); + } + + sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.BD, 0, 0, MmcDiscStructureFormat.BD_SpareAreaInformation, 0, dev.Timeout, out duration); + if(!sense) + { + tmpBuf = new byte[cmdBuf.Length - 4]; + Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); + sidecar.OpticalDisc[0].SAI = new DumpType(); + sidecar.OpticalDisc[0].SAI.Image = outputPrefix + ".sai.bin"; + sidecar.OpticalDisc[0].SAI.Size = tmpBuf.Length; + sidecar.OpticalDisc[0].SAI.Checksums = Checksum.GetChecksums(tmpBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].SAI.Image, tmpBuf); + } + } + #endregion Writable Blu-ray only + } + } + #endregion MultiMediaDevice + else + { + compactDisc = false; + sidecar.BlockMedia = new BlockMediaType[1]; + sidecar.BlockMedia[0] = new BlockMediaType(); + + // All USB flash drives report as removable, even if the media is not removable + if(!dev.IsRemovable || dev.IsUSB) + { + if(dev.IsUSB) + { + sidecar.BlockMedia[0].USB = new USBType(); + sidecar.BlockMedia[0].USB.ProductID = dev.USBProductID; + sidecar.BlockMedia[0].USB.VendorID = dev.USBVendorID; + sidecar.BlockMedia[0].USB.Descriptors = new DumpType(); + sidecar.BlockMedia[0].USB.Descriptors.Image = outputPrefix + ".usbdescriptors.bin"; + sidecar.BlockMedia[0].USB.Descriptors.Size = dev.USBDescriptors.Length; + sidecar.BlockMedia[0].USB.Descriptors.Checksums = Checksum.GetChecksums(dev.USBDescriptors).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.BlockMedia[0].USB.Descriptors.Image, dev.USBDescriptors); + } + + if(dev.Type == DeviceType.ATAPI) + { + Decoders.ATA.AtaErrorRegistersCHS errorRegs; + sense = dev.AtapiIdentify(out cmdBuf, out errorRegs); + if(!sense) + { + sidecar.BlockMedia[0].ATA = new ATAType(); + sidecar.BlockMedia[0].ATA.Identify = new DumpType(); + sidecar.BlockMedia[0].ATA.Identify.Image = outputPrefix + ".identify.bin"; + sidecar.BlockMedia[0].ATA.Identify.Size = cmdBuf.Length; + sidecar.BlockMedia[0].ATA.Identify.Checksums = Checksum.GetChecksums(cmdBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.BlockMedia[0].ATA.Identify.Image, cmdBuf); + } + } + + sense = dev.ScsiInquiry(out cmdBuf, out senseBuf); + if(!sense) + { + sidecar.BlockMedia[0].SCSI = new SCSIType(); + sidecar.BlockMedia[0].SCSI.Inquiry = new DumpType(); + sidecar.BlockMedia[0].SCSI.Inquiry.Image = outputPrefix + ".inquiry.bin"; + sidecar.BlockMedia[0].SCSI.Inquiry.Size = cmdBuf.Length; + sidecar.BlockMedia[0].SCSI.Inquiry.Checksums = Checksum.GetChecksums(cmdBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.BlockMedia[0].SCSI.Inquiry.Image, cmdBuf); + + sense = dev.ScsiInquiry(out cmdBuf, out senseBuf, 0x00); + if(!sense) + { + byte[] pages = Decoders.SCSI.EVPD.DecodePage00(cmdBuf); + + if(pages != null) + { + List evpds = new List(); + foreach(byte page in pages) + { + sense = dev.ScsiInquiry(out cmdBuf, out senseBuf, page); + if(!sense) + { + EVPDType evpd = new EVPDType(); + evpd.Image = string.Format("{0}.evpd_{1:X2}h.bin", outputPrefix, page); + evpd.Checksums = Checksum.GetChecksums(cmdBuf).ToArray(); + evpd.Size = cmdBuf.Length; + evpd.Checksums = Checksum.GetChecksums(cmdBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", evpd.Image, cmdBuf); + evpds.Add(evpd); + } + } + + if(evpds.Count > 0) + sidecar.BlockMedia[0].SCSI.EVPD = evpds.ToArray(); + } + } + + sense = dev.ModeSense10(out cmdBuf, out senseBuf, false, true, ScsiModeSensePageControl.Current, 0x3F, 0xFF, 5, out duration); + if(!sense || dev.Error) + { + sense = dev.ModeSense10(out cmdBuf, out senseBuf, false, true, ScsiModeSensePageControl.Current, 0x3F, 0x00, 5, out duration); + } + + Decoders.SCSI.Modes.DecodedMode? decMode = null; + + if(!sense && !dev.Error) + { + if(Decoders.SCSI.Modes.DecodeMode10(cmdBuf, dev.SCSIType).HasValue) + { + decMode = Decoders.SCSI.Modes.DecodeMode10(cmdBuf, dev.SCSIType); + sidecar.BlockMedia[0].SCSI.ModeSense10 = new DumpType(); + sidecar.BlockMedia[0].SCSI.ModeSense10.Image = outputPrefix + ".modesense10.bin"; + sidecar.BlockMedia[0].SCSI.ModeSense10.Size = cmdBuf.Length; + sidecar.BlockMedia[0].SCSI.ModeSense10.Checksums = Checksum.GetChecksums(cmdBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.BlockMedia[0].SCSI.ModeSense10.Image, cmdBuf); + } + } + + sense = dev.ModeSense6(out cmdBuf, out senseBuf, false, ScsiModeSensePageControl.Current, 0x3F, 0x00, 5, out duration); + if(sense || dev.Error) + sense = dev.ModeSense6(out cmdBuf, out senseBuf, false, ScsiModeSensePageControl.Current, 0x3F, 0x00, 5, out duration); + if(sense || dev.Error) + sense = dev.ModeSense(out cmdBuf, out senseBuf, 5, out duration); + + if(!sense && !dev.Error) + { + if(Decoders.SCSI.Modes.DecodeMode6(cmdBuf, dev.SCSIType).HasValue) + { + decMode = Decoders.SCSI.Modes.DecodeMode6(cmdBuf, dev.SCSIType); + sidecar.BlockMedia[0].SCSI.ModeSense = new DumpType(); + sidecar.BlockMedia[0].SCSI.ModeSense.Image = outputPrefix + ".modesense.bin"; + sidecar.BlockMedia[0].SCSI.ModeSense.Size = cmdBuf.Length; + sidecar.BlockMedia[0].SCSI.ModeSense.Checksums = Checksum.GetChecksums(cmdBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.BlockMedia[0].SCSI.ModeSense.Image, cmdBuf); + } + } + + if(decMode.HasValue) + { + scsiMediumType = (byte)decMode.Value.Header.MediumType; + if(decMode.Value.Header.BlockDescriptors != null && decMode.Value.Header.BlockDescriptors.Length >= 1) + scsiDensityCode = (byte)decMode.Value.Header.BlockDescriptors[0].Density; + + foreach(Decoders.SCSI.Modes.ModePage modePage in decMode.Value.Pages) + containsFloppyPage |= modePage.Page == 0x05; + } + } + } + } + + if(dskType == MediaType.Unknown) + dskType = MediaTypeFromSCSI.Get((byte)dev.SCSIType, dev.Manufacturer, dev.Model, scsiMediumType, scsiDensityCode, blocks, blockSize); + + if(dskType == MediaType.Unknown && dev.IsUSB && containsFloppyPage) + dskType = MediaType.FlashDrive; + + DicConsole.WriteLine("Media identified as {0}", dskType); + + byte[] readBuffer; + uint blocksToRead = 64; + + ulong errored = 0; + + aborted = false; + System.Console.CancelKeyPress += (sender, e) => + { + e.Cancel = aborted = true; + }; + + // TODO: Raw reading + bool read6 = false, read10 = false, read12 = false, read16 = false, readcd = false; + bool readLong10 = false, readLong16 = false, hldtstReadRaw = false, readLongDvd = false; + bool plextorReadRaw = false, syqReadLong6 = false, syqReadLong10 = false; + + #region CompactDisc dump + if(compactDisc) + { + if(toc == null) + { + DicConsole.ErrorWriteLine("Error trying to decode TOC..."); + return; + } + + if(dumpRaw) + { + throw new NotImplementedException("Raw CD dumping not yet implemented"); + } + else + { + // TODO: Check subchannel capabilities + readcd = !dev.ReadCd(out readBuffer, out senseBuf, 0, 2448, 1, MmcSectorTypes.AllTypes, false, false, true, MmcHeaderCodes.AllHeaders, + true, true, MmcErrorField.None, MmcSubchannel.Raw, dev.Timeout, out duration); + + if(readcd) + DicConsole.WriteLine("Using MMC READ CD command."); + } + + DicConsole.WriteLine("Trying to read Lead-In..."); + bool gotLeadIn = false; + int leadInSectorsGood = 0, leadInSectorsTotal = 0; + + dumpFile = new DataFile(outputPrefix + ".leadin.bin"); + dataChk = new Checksum(); + + start = DateTime.UtcNow; + + readBuffer = null; + + for(int leadInBlock = -150; leadInBlock < 0; leadInBlock++) + { + if(aborted) + break; + + double cmdDuration = 0; + +#pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator + if(currentSpeed > maxSpeed && currentSpeed != 0) + maxSpeed = currentSpeed; + if(currentSpeed < minSpeed && currentSpeed != 0) + minSpeed = currentSpeed; +#pragma warning restore RECS0018 // Comparison of floating point numbers with equality operator + + DicConsole.Write("\rTrying to read lead-in sector {0} ({1:F3} MiB/sec.)", leadInBlock, currentSpeed); + + sense = dev.ReadCd(out readBuffer, out senseBuf, (uint)leadInBlock, 2448, 1, MmcSectorTypes.AllTypes, false, false, true, MmcHeaderCodes.AllHeaders, + true, true, MmcErrorField.None, MmcSubchannel.Raw, dev.Timeout, out cmdDuration); + + if(!sense && !dev.Error) + { + dataChk.Update(readBuffer); + dumpFile.Write(readBuffer); + gotLeadIn = true; + leadInSectorsGood++; + leadInSectorsTotal++; + } + else + { + if(gotLeadIn) + { + // Write empty data + dataChk.Update(new byte[2448]); + dumpFile.Write(new byte[2448]); + leadInSectorsTotal++; + } + } + +#pragma warning disable IDE0004 // Remove Unnecessary Cast + currentSpeed = ((double)2448 / (double)1048576) / (cmdDuration / (double)1000); +#pragma warning restore IDE0004 // Remove Unnecessary Cast + } + + dumpFile.Close(); + if(leadInSectorsGood > 0) + { + sidecar.OpticalDisc[0].LeadIn = new BorderType[1]; + sidecar.OpticalDisc[0].LeadIn[0] = new BorderType(); + sidecar.OpticalDisc[0].LeadIn[0].Image = outputPrefix + ".leadin.bin"; + sidecar.OpticalDisc[0].LeadIn[0].Checksums = dataChk.End().ToArray(); + sidecar.OpticalDisc[0].LeadIn[0].Size = leadInSectorsTotal * 2448; + } + else + File.Delete(outputPrefix + ".leadin.bin"); + + DicConsole.WriteLine(); + DicConsole.WriteLine("Got {0} lead-in sectors.", leadInSectorsGood); + + while(true) + { + if(readcd) + { + sense = dev.ReadCd(out readBuffer, out senseBuf, 0, 2448, blocksToRead, MmcSectorTypes.AllTypes, false, false, true, MmcHeaderCodes.AllHeaders, + true, true, MmcErrorField.None, MmcSubchannel.Raw, dev.Timeout, out duration); + if(dev.Error) + blocksToRead /= 2; + } + + if(!dev.Error || blocksToRead == 1) + break; + } + + if(dev.Error) + { + DicConsole.ErrorWriteLine("Device error {0} trying to guess ideal transfer length.", dev.LastError); + return; + } + + DicConsole.WriteLine("Reading {0} sectors at a time.", blocksToRead); + + dumpFile = new DataFile(outputPrefix + ".bin"); + mhddLog = new MHDDLog(outputPrefix + ".mhddlog.bin", dev, blocks, blockSize, blocksToRead); + ibgLog = new IBGLog(outputPrefix + ".ibg", 0x0008); + + start = DateTime.UtcNow; + for(ulong i = 0; i < blocks; i += blocksToRead) + { + if(aborted) + break; + + double cmdDuration = 0; + + if((blocks - i) < blocksToRead) + blocksToRead = (uint)(blocks - i); + +#pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator + if(currentSpeed > maxSpeed && currentSpeed != 0) + maxSpeed = currentSpeed; + if(currentSpeed < minSpeed && currentSpeed != 0) + minSpeed = currentSpeed; +#pragma warning restore RECS0018 // Comparison of floating point numbers with equality operator + + DicConsole.Write("\rReading sector {0} of {1} ({2:F3} MiB/sec.)", i, blocks, currentSpeed); + + if(readcd) + { + sense = dev.ReadCd(out readBuffer, out senseBuf, (uint)i, 2448, blocksToRead, MmcSectorTypes.AllTypes, false, false, true, MmcHeaderCodes.AllHeaders, + true, true, MmcErrorField.None, MmcSubchannel.Raw, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + + if(!sense && !dev.Error) + { + mhddLog.Write(i, cmdDuration); + ibgLog.Write(i, currentSpeed * 1024); + dumpFile.Write(readBuffer); + } + else + { + // TODO: Reset device after X errors + if(stopOnError) + return; // TODO: Return more cleanly + + // Write empty data + dumpFile.Write(new byte[2448 * blocksToRead]); + + // TODO: Record error on mapfile + + errored += blocksToRead; + unreadableSectors.Add(i); + DicConsole.DebugWriteLine("Dump-Media", "READ error:\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); + if(cmdDuration < 500) + mhddLog.Write(i, 65535); + else + mhddLog.Write(i, cmdDuration); + + ibgLog.Write(i, 0); + } + +#pragma warning disable IDE0004 // Remove Unnecessary Cast + currentSpeed = ((double)2448 * blocksToRead / (double)1048576) / (cmdDuration / (double)1000); +#pragma warning restore IDE0004 // Remove Unnecessary Cast + } + DicConsole.WriteLine(); + end = DateTime.UtcNow; + mhddLog.Close(); +#pragma warning disable IDE0004 // Remove Unnecessary Cast + ibgLog.Close(dev, blocks, blockSize, (end - start).TotalSeconds, currentSpeed * 1024, (((double)blockSize * (double)(blocks + 1)) / 1024) / (totalDuration / 1000), devicePath); +#pragma warning restore IDE0004 // Remove Unnecessary Cast + + #region Compact Disc Error handling + if(unreadableSectors.Count > 0 && !aborted) + { + List tmpList = new List(); + + foreach(ulong ur in unreadableSectors) + { + for(ulong i = ur; i < ur + blocksToRead; i++) + tmpList.Add(i); + } + + tmpList.Sort(); + + int pass = 0; + bool forward = true; + bool runningPersistent = false; + + unreadableSectors = tmpList; + + cdRepeatRetry: + ulong[] tmpArray = unreadableSectors.ToArray(); + foreach(ulong badSector in tmpArray) + { + if(aborted) + break; + + double cmdDuration = 0; + + DicConsole.Write("\rRetrying sector {0}, pass {1}, {3}{2}", badSector, pass + 1, forward ? "forward" : "reverse", runningPersistent ? "recovering partial data, " : ""); + + if(readcd) + { + sense = dev.ReadCd(out readBuffer, out senseBuf, (uint)badSector, 2448, blocksToRead, MmcSectorTypes.AllTypes, false, false, true, MmcHeaderCodes.AllHeaders, + true, true, MmcErrorField.None, MmcSubchannel.Raw, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + + if(!sense && !dev.Error) + { + unreadableSectors.Remove(badSector); + dumpFile.WriteAt(readBuffer, badSector, blockSize); + } + else if(runningPersistent) + dumpFile.WriteAt(readBuffer, badSector, blockSize); + } + + if(pass < retryPasses && !aborted && unreadableSectors.Count > 0) + { + pass++; + forward = !forward; + unreadableSectors.Sort(); + unreadableSectors.Reverse(); + goto cdRepeatRetry; + } + + Decoders.SCSI.Modes.DecodedMode? currentMode = null; + Decoders.SCSI.Modes.ModePage? currentModePage = null; + byte[] md6 = null; + byte[] md10 = null; + + if(!runningPersistent && persistent) + { + sense = dev.ModeSense6(out readBuffer, out senseBuf, false, ScsiModeSensePageControl.Current, 0x01, dev.Timeout, out duration); + if(sense) + { + sense = dev.ModeSense10(out readBuffer, out senseBuf, false, ScsiModeSensePageControl.Current, 0x01, dev.Timeout, out duration); + if(!sense) + currentMode = Decoders.SCSI.Modes.DecodeMode10(readBuffer, dev.SCSIType); + } + else + currentMode = Decoders.SCSI.Modes.DecodeMode6(readBuffer, dev.SCSIType); + + if(currentMode.HasValue) + currentModePage = currentMode.Value.Pages[0]; + + Decoders.SCSI.Modes.ModePage_01_MMC pgMMC = new Decoders.SCSI.Modes.ModePage_01_MMC(); + pgMMC.PS = false; + pgMMC.ReadRetryCount = 255; + pgMMC.Parameter = 0x20; + + Decoders.SCSI.Modes.DecodedMode md = new Decoders.SCSI.Modes.DecodedMode(); + md.Header = new Decoders.SCSI.Modes.ModeHeader(); + md.Pages = new Decoders.SCSI.Modes.ModePage[1]; + md.Pages[0] = new Decoders.SCSI.Modes.ModePage(); + md.Pages[0].Page = 0x01; + md.Pages[0].Subpage = 0x00; + md.Pages[0].PageResponse = Decoders.SCSI.Modes.EncodeModePage_01_MMC(pgMMC); + md6 = Decoders.SCSI.Modes.EncodeMode6(md, dev.SCSIType); + md10 = Decoders.SCSI.Modes.EncodeMode10(md, dev.SCSIType); + + sense = dev.ModeSelect(md6, out senseBuf, true, false, dev.Timeout, out duration); + if(sense) + { + sense = dev.ModeSelect10(md10, out senseBuf, true, false, dev.Timeout, out duration); + } + + runningPersistent = true; + if(!sense && !dev.Error) + { + pass--; + goto cdRepeatRetry; + } + } + else if(runningPersistent && persistent && currentModePage.HasValue) + { + Decoders.SCSI.Modes.DecodedMode md = new Decoders.SCSI.Modes.DecodedMode(); + md.Header = new Decoders.SCSI.Modes.ModeHeader(); + md.Pages = new Decoders.SCSI.Modes.ModePage[1]; + md.Pages[0] = currentModePage.Value; + md6 = Decoders.SCSI.Modes.EncodeMode6(md, dev.SCSIType); + md10 = Decoders.SCSI.Modes.EncodeMode10(md, dev.SCSIType); + + sense = dev.ModeSelect(md6, out senseBuf, true, false, dev.Timeout, out duration); + if(sense) + { + sense = dev.ModeSelect10(md10, out senseBuf, true, false, dev.Timeout, out duration); + } + } + + DicConsole.WriteLine(); + } + #endregion Compact Disc Error handling + + dataChk = new Checksum(); + dumpFile.Seek(0, SeekOrigin.Begin); + blocksToRead = 500; + + for(ulong i = 0; i < blocks; i += blocksToRead) + { + if(aborted) + break; + + if((blocks - i) < blocksToRead) + blocksToRead = (uint)(blocks - i); + + DicConsole.Write("\rChecksumming sector {0} of {1} ({2:F3} MiB/sec.)", i, blocks, currentSpeed); + + DateTime chkStart = DateTime.UtcNow; + byte[] dataToCheck = new byte[blockSize * blocksToRead]; + dumpFile.Read(dataToCheck, 0, (int)(blockSize * blocksToRead)); + dataChk.Update(dataToCheck); + DateTime chkEnd = DateTime.UtcNow; + + double chkDuration = (chkEnd - chkStart).TotalMilliseconds; + totalChkDuration += chkDuration; + +#pragma warning disable IDE0004 // Remove Unnecessary Cast + currentSpeed = ((double)blockSize * blocksToRead / (double)1048576) / (chkDuration / (double)1000); +#pragma warning restore IDE0004 // Remove Unnecessary Cast + } + DicConsole.WriteLine(); + dumpFile.Close(); + end = DateTime.UtcNow; + + // TODO: Correct this + sidecar.OpticalDisc[0].Checksums = dataChk.End().ToArray(); + sidecar.OpticalDisc[0].DumpHardwareArray = new DumpHardwareType[1]; + sidecar.OpticalDisc[0].DumpHardwareArray[0] = new DumpHardwareType(); + sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents = new ExtentType[1]; + sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents[0] = new ExtentType(); + sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents[0].Start = 0; + sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents[0].End = (int)(blocks - 1); + sidecar.OpticalDisc[0].DumpHardwareArray[0].Manufacturer = dev.Manufacturer; + sidecar.OpticalDisc[0].DumpHardwareArray[0].Model = dev.Model; + sidecar.OpticalDisc[0].DumpHardwareArray[0].Revision = dev.Revision; + sidecar.OpticalDisc[0].DumpHardwareArray[0].Software = new SoftwareType(); + sidecar.OpticalDisc[0].DumpHardwareArray[0].Software.Name = "DiscImageChef"; + sidecar.OpticalDisc[0].DumpHardwareArray[0].Software.OperatingSystem = dev.PlatformID.ToString(); + sidecar.OpticalDisc[0].DumpHardwareArray[0].Software.Version = typeof(SCSI).Assembly.GetName().Version.ToString(); + sidecar.OpticalDisc[0].Image = new ImageType(); + sidecar.OpticalDisc[0].Image.format = "Raw disk image (sector by sector copy)"; + sidecar.OpticalDisc[0].Image.Value = outputPrefix + ".bin"; + sidecar.OpticalDisc[0].Sessions = 1; + sidecar.OpticalDisc[0].Tracks = new[] { 1 }; + sidecar.OpticalDisc[0].Track = new Schemas.TrackType[1]; + sidecar.OpticalDisc[0].Track[0] = new Schemas.TrackType(); + sidecar.OpticalDisc[0].Track[0].BytesPerSector = (int)blockSize; + sidecar.OpticalDisc[0].Track[0].Checksums = sidecar.OpticalDisc[0].Checksums; + sidecar.OpticalDisc[0].Track[0].EndSector = (long)(blocks - 1); + sidecar.OpticalDisc[0].Track[0].Image = new ImageType(); + sidecar.OpticalDisc[0].Track[0].Image.format = "BINARY"; + sidecar.OpticalDisc[0].Track[0].Image.offset = 0; + sidecar.OpticalDisc[0].Track[0].Image.offsetSpecified = true; + sidecar.OpticalDisc[0].Track[0].Image.Value = sidecar.OpticalDisc[0].Image.Value; + sidecar.OpticalDisc[0].Track[0].Sequence = new TrackSequenceType(); + sidecar.OpticalDisc[0].Track[0].Sequence.Session = 1; + sidecar.OpticalDisc[0].Track[0].Sequence.TrackNumber = 1; + sidecar.OpticalDisc[0].Track[0].Size = (long)(blocks * blockSize); + sidecar.OpticalDisc[0].Track[0].StartSector = 0; + sidecar.OpticalDisc[0].Track[0].TrackType1 = TrackTypeTrackType.mode1; + sidecar.OpticalDisc[0].Dimensions = Metadata.Dimensions.DimensionsFromMediaType(dskType); + string xmlDskTyp, xmlDskSubTyp; + Metadata.MediaType.MediaTypeToString(dskType, out xmlDskTyp, out xmlDskSubTyp); + sidecar.OpticalDisc[0].DiscType = xmlDskTyp; + sidecar.OpticalDisc[0].DiscSubType = xmlDskSubTyp; + } + #endregion CompactDisc dump + #region Xbox Game Disc + else if(isXbox) + { + byte[] ssBuf; + sense = dev.KreonExtractSS(out ssBuf, out senseBuf, dev.Timeout, out duration); + if(sense) + { + DicConsole.ErrorWriteLine("Cannot get Xbox Security Sector, not continuing."); + return; + } + + Decoders.Xbox.SS.SecuritySector? xboxSS = Decoders.Xbox.SS.Decode(ssBuf); + if(!xboxSS.HasValue) + { + DicConsole.ErrorWriteLine("Cannot decode Xbox Security Sector, not continuing."); + return; + } + + + // TODO: Correct metadata + /*sidecar.OpticalDisc[0].XboxSecuritySectors = new DumpType(); + sidecar.OpticalDisc[0].XboxSecuritySectors.Image = outputPrefix + ".bca.bin"; + sidecar.OpticalDisc[0].XboxSecuritySectors.Size = cmdBuf.Length; + sidecar.OpticalDisc[0].XboxSecuritySectors.Checksums = Checksum.GetChecksums(cmbBuf).ToArray(); + DataFile.WriteTo("SCSI Dump", sidecar.OpticalDisc[0].XboxSecuritySectors.Image, tmpBuf);*/ + DataFile.WriteTo("SCSI Dump", outputPrefix + ".ss.bin", cmdBuf); + + ulong l0Video, l1Video, middleZone, gameSize, totalSize, layerBreak; + + // Get video partition size + DicConsole.DebugWriteLine("Dump-media command", "Getting video partition size"); + sense = dev.KreonLock(out senseBuf, dev.Timeout, out duration); + if(sense) + { + DicConsole.ErrorWriteLine("Cannot lock drive, not continuing."); + return; + } + sense = dev.ReadCapacity(out readBuffer, out senseBuf, dev.Timeout, out duration); + if(sense) + { + DicConsole.ErrorWriteLine("Cannot get disc capacity."); + return; + } + totalSize = (ulong)((readBuffer[0] << 24) + (readBuffer[1] << 16) + (readBuffer[2] << 8) + (readBuffer[3])); + sense = dev.ReadDiscStructure(out readBuffer, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.PhysicalInformation, 0, 0, out duration); + if(sense) + { + DicConsole.ErrorWriteLine("Cannot get PFI."); + return; + } + DicConsole.DebugWriteLine("Dump-media command", "Video partition total size: {0} sectors", totalSize); + l0Video = Decoders.DVD.PFI.Decode(readBuffer).Value.Layer0EndPSN - Decoders.DVD.PFI.Decode(readBuffer).Value.DataAreaStartPSN + 1; + l1Video = totalSize - l0Video + 1; + + // Get game partition size + DicConsole.DebugWriteLine("Dump-media command", "Getting game partition size"); + sense = dev.KreonUnlockXtreme(out senseBuf, dev.Timeout, out duration); + if(sense) + { + DicConsole.ErrorWriteLine("Cannot unlock drive, not continuing."); + return; + } + sense = dev.ReadCapacity(out readBuffer, out senseBuf, dev.Timeout, out duration); + if(sense) + { + DicConsole.ErrorWriteLine("Cannot get disc capacity."); + return; + } + gameSize = (ulong)((readBuffer[0] << 24) + (readBuffer[1] << 16) + (readBuffer[2] << 8) + (readBuffer[3])) + 1; + DicConsole.DebugWriteLine("Dump-media command", "Game partition total size: {0} sectors", gameSize); + + // Get middle zone size + DicConsole.DebugWriteLine("Dump-media command", "Getting middle zone size"); + sense = dev.KreonUnlockWxripper(out senseBuf, dev.Timeout, out duration); + if(sense) + { + DicConsole.ErrorWriteLine("Cannot unlock drive, not continuing."); + return; + } + sense = dev.ReadCapacity(out readBuffer, out senseBuf, dev.Timeout, out duration); + if(sense) + { + DicConsole.ErrorWriteLine("Cannot get disc capacity."); + return; + } + totalSize = (ulong)((readBuffer[0] << 24) + (readBuffer[1] << 16) + (readBuffer[2] << 8) + (readBuffer[3])); + sense = dev.ReadDiscStructure(out readBuffer, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.PhysicalInformation, 0, 0, out duration); + if(sense) + { + DicConsole.ErrorWriteLine("Cannot get PFI."); + return; + } + DicConsole.DebugWriteLine("Dump-media command", "Unlocked total size: {0} sectors", totalSize); + middleZone = totalSize - (Decoders.DVD.PFI.Decode(readBuffer).Value.Layer0EndPSN - Decoders.DVD.PFI.Decode(readBuffer).Value.DataAreaStartPSN + 1) - gameSize + 1; + + totalSize = l0Video + l1Video + middleZone * 2 + gameSize; + layerBreak = l0Video + middleZone + gameSize / 2; + + DicConsole.WriteLine("Video layer 0 size: {0} sectors", l0Video); + DicConsole.WriteLine("Video layer 1 size: {0} sectors", l1Video); + DicConsole.WriteLine("Middle zone size: {0} sectors", middleZone); + DicConsole.WriteLine("Game data size: {0} sectors", gameSize); + DicConsole.WriteLine("Total size: {0} sectors", totalSize); + DicConsole.WriteLine("Real layer break: {0}", layerBreak); + DicConsole.WriteLine(); + + read12 = !dev.Read12(out readBuffer, out senseBuf, 0, false, true, false, false, 0, blockSize, 0, 1, false, dev.Timeout, out duration); + if(!read12) + { + DicConsole.ErrorWriteLine("Cannot read medium, aborting scan..."); + return; + } + + DicConsole.WriteLine("Using SCSI READ (12) command."); + + while(true) + { + if(read12) + { + sense = dev.Read12(out readBuffer, out senseBuf, 0, false, false, false, false, 0, blockSize, 0, blocksToRead, false, dev.Timeout, out duration); + if(dev.Error) + blocksToRead /= 2; + } + + if(!dev.Error || blocksToRead == 1) + break; + } + + if(dev.Error) + { + DicConsole.ErrorWriteLine("Device error {0} trying to guess ideal transfer length.", dev.LastError); + return; + } + + + DicConsole.WriteLine("Reading {0} sectors at a time.", blocksToRead); + + mhddLog = new MHDDLog(outputPrefix + ".mhddlog.bin", dev, blocks, blockSize, blocksToRead); + ibgLog = new IBGLog(outputPrefix + ".ibg", currentProfile); + dumpFile = new DataFile(outputPrefix + ".bin"); + + start = DateTime.UtcNow; + + readBuffer = null; + + ulong currentSector = 0; + double cmdDuration = 0; + uint saveBlocksToRead = blocksToRead; + + for(int e = 0; e <= 16; e++) + { + ulong extentStart, extentEnd; + // Extents + if(e < 16) + { + if(xboxSS.Value.Extents[e].StartPSN <= xboxSS.Value.Layer0EndPSN) + extentStart = xboxSS.Value.Extents[e].StartPSN - 0x30000; + else + extentStart = (xboxSS.Value.Layer0EndPSN + 1) * 2 - ((xboxSS.Value.Extents[e].StartPSN ^ 0xFFFFFF) + 1) - 0x30000; + if(xboxSS.Value.Extents[e].EndPSN <= xboxSS.Value.Layer0EndPSN) + extentEnd = xboxSS.Value.Extents[e].EndPSN - 0x30000; + else + extentEnd = (xboxSS.Value.Layer0EndPSN + 1) * 2 - ((xboxSS.Value.Extents[e].EndPSN ^ 0xFFFFFF) + 1) - 0x30000; + } + // After last extent + else + { + extentStart = blocks; + extentEnd = blocks; + } + + for(ulong i = currentSector; i < extentStart; i += blocksToRead) + { + saveBlocksToRead = blocksToRead; + if(aborted) + break; + + if((extentStart - i) < blocksToRead) + blocksToRead = (uint)(extentStart - i); + +#pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator + if(currentSpeed > maxSpeed && currentSpeed != 0) + maxSpeed = currentSpeed; + if(currentSpeed < minSpeed && currentSpeed != 0) + minSpeed = currentSpeed; +#pragma warning restore RECS0018 // Comparison of floating point numbers with equality operator + + DicConsole.Write("\rReading sector {0} of {1} ({2:F3} MiB/sec.)", i, totalSize, currentSpeed); + + sense = dev.Read12(out readBuffer, out senseBuf, 0, false, false, false, false, (uint)i, blockSize, 0, blocksToRead, false, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + + if(!sense && !dev.Error) + { + mhddLog.Write(i, cmdDuration); + ibgLog.Write(i, currentSpeed * 1024); + dumpFile.Write(readBuffer); + } + else + { + // TODO: Reset device after X errors + if(stopOnError) + return; // TODO: Return more cleanly + + // Write empty data + dumpFile.Write(new byte[blockSize * blocksToRead]); + + // TODO: Record error on mapfile + + errored += blocksToRead; + unreadableSectors.Add(i); + DicConsole.DebugWriteLine("Dump-Media", "READ error:\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); + if(cmdDuration < 500) + mhddLog.Write(i, 65535); + else + mhddLog.Write(i, cmdDuration); + + ibgLog.Write(i, 0); + } + +#pragma warning disable IDE0004 // Remove Unnecessary Cast + currentSpeed = ((double)blockSize * blocksToRead / (double)1048576) / (cmdDuration / (double)1000); +#pragma warning restore IDE0004 // Remove Unnecessary Cast + blocksToRead = saveBlocksToRead; + } + + for(ulong i = extentStart; i <= extentEnd; i += blocksToRead) + { + saveBlocksToRead = blocksToRead; + if(aborted) + break; + + if((extentEnd - i) < blocksToRead) + blocksToRead = (uint)(extentEnd - i) + 1; + + mhddLog.Write(i, cmdDuration); + ibgLog.Write(i, currentSpeed * 1024); + dumpFile.Write(new byte[blocksToRead * 2048]); + blocksToRead = saveBlocksToRead; + } + + currentSector = extentEnd + 1; + if(currentSector >= blocks) + break; + } + + // Middle Zone D + for(ulong middle = 0; middle < (middleZone - 1); middle += blocksToRead) + { + if(aborted) + break; + + if(((middleZone - 1) - middle) < blocksToRead) + blocksToRead = (uint)((middleZone - 1) - middle); + + DicConsole.Write("\rReading sector {0} of {1} ({2:F3} MiB/sec.)", middle + currentSector, totalSize, currentSpeed); + + mhddLog.Write(middle + currentSector, cmdDuration); + ibgLog.Write(middle + currentSector, currentSpeed * 1024); + dumpFile.Write(new byte[blockSize * blocksToRead]); + + currentSector += blocksToRead; + } + + blocksToRead = saveBlocksToRead; + + sense = dev.KreonLock(out senseBuf, dev.Timeout, out duration); + if(sense) + { + DicConsole.ErrorWriteLine("Cannot lock drive, not continuing."); + return; + } + sense = dev.ReadCapacity(out readBuffer, out senseBuf, dev.Timeout, out duration); + if(sense) + { + DicConsole.ErrorWriteLine("Cannot get disc capacity."); + return; + } + + // Video Layer 1 + for(ulong l1 = l0Video; l1 < (l0Video + l1Video); l1 += blocksToRead) + { + if(aborted) + break; + + if(((l0Video + l1Video) - l1) < blocksToRead) + blocksToRead = (uint)((l0Video + l1Video) - l1); + +#pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator + if(currentSpeed > maxSpeed && currentSpeed != 0) + maxSpeed = currentSpeed; + if(currentSpeed < minSpeed && currentSpeed != 0) + minSpeed = currentSpeed; +#pragma warning restore RECS0018 // Comparison of floating point numbers with equality operator + + DicConsole.Write("\rReading sector {0} of {1} ({2:F3} MiB/sec.)", currentSector, totalSize, currentSpeed); + + sense = dev.Read12(out readBuffer, out senseBuf, 0, false, false, false, false, (uint)l1, blockSize, 0, blocksToRead, false, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + + if(!sense && !dev.Error) + { + mhddLog.Write(currentSector, cmdDuration); + ibgLog.Write(currentSector, currentSpeed * 1024); + dumpFile.Write(readBuffer); + } + else + { + // TODO: Reset device after X errors + if(stopOnError) + return; // TODO: Return more cleanly + + // Write empty data + dumpFile.Write(new byte[blockSize * blocksToRead]); + + // TODO: Record error on mapfile + + // TODO: Handle errors in video partition + //errored += blocksToRead; + //unreadableSectors.Add(l1); + DicConsole.DebugWriteLine("Dump-Media", "READ error:\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); + if(cmdDuration < 500) + mhddLog.Write(l1, 65535); + else + mhddLog.Write(l1, cmdDuration); + + ibgLog.Write(l1, 0); + } + +#pragma warning disable IDE0004 // Remove Unnecessary Cast + currentSpeed = ((double)blockSize * blocksToRead / (double)1048576) / (cmdDuration / (double)1000); +#pragma warning restore IDE0004 // Remove Unnecessary Cast + currentSector += blocksToRead; + } + + sense = dev.KreonUnlockWxripper(out senseBuf, dev.Timeout, out duration); + if(sense) + { + DicConsole.ErrorWriteLine("Cannot unlock drive, not continuing."); + return; + } + sense = dev.ReadCapacity(out readBuffer, out senseBuf, dev.Timeout, out duration); + if(sense) + { + DicConsole.ErrorWriteLine("Cannot get disc capacity."); + return; + } + + end = DateTime.UtcNow; + DicConsole.WriteLine(); + mhddLog.Close(); +#pragma warning disable IDE0004 // Remove Unnecessary Cast + ibgLog.Close(dev, blocks, blockSize, (end - start).TotalSeconds, currentSpeed * 1024, (((double)blockSize * (double)(blocks + 1)) / 1024) / (totalDuration / 1000), devicePath); +#pragma warning restore IDE0004 // Remove Unnecessary Cast + + #region Error handling + if(unreadableSectors.Count > 0 && !aborted) + { + List tmpList = new List(); + + foreach(ulong ur in unreadableSectors) + { + for(ulong i = ur; i < ur + blocksToRead; i++) + tmpList.Add(i); + } + + tmpList.Sort(); + + int pass = 0; + bool forward = true; + bool runningPersistent = false; + + unreadableSectors = tmpList; + + repeatRetry: + ulong[] tmpArray = unreadableSectors.ToArray(); + foreach(ulong badSector in tmpArray) + { + if(aborted) + break; + + cmdDuration = 0; + + DicConsole.Write("\rRetrying sector {0}, pass {1}, {3}{2}", badSector, pass + 1, forward ? "forward" : "reverse", runningPersistent ? "recovering partial data, " : ""); + + sense = dev.Read12(out readBuffer, out senseBuf, 0, false, false, false, false, (uint)badSector, blockSize, 0, 1, false, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + + if(!sense && !dev.Error) + { + unreadableSectors.Remove(badSector); + dumpFile.WriteAt(readBuffer, badSector, blockSize); + } + else if(runningPersistent) + dumpFile.WriteAt(readBuffer, badSector, blockSize); + } + + if(pass < retryPasses && !aborted && unreadableSectors.Count > 0) + { + pass++; + forward = !forward; + unreadableSectors.Sort(); + unreadableSectors.Reverse(); + goto repeatRetry; + } + + Decoders.SCSI.Modes.DecodedMode? currentMode = null; + Decoders.SCSI.Modes.ModePage? currentModePage = null; + byte[] md6 = null; + byte[] md10 = null; + + if(!runningPersistent && persistent) + { + sense = dev.ModeSense6(out readBuffer, out senseBuf, false, ScsiModeSensePageControl.Current, 0x01, dev.Timeout, out duration); + if(sense) + { + sense = dev.ModeSense10(out readBuffer, out senseBuf, false, ScsiModeSensePageControl.Current, 0x01, dev.Timeout, out duration); + if(!sense) + currentMode = Decoders.SCSI.Modes.DecodeMode10(readBuffer, dev.SCSIType); + } + else + currentMode = Decoders.SCSI.Modes.DecodeMode6(readBuffer, dev.SCSIType); + + if(currentMode.HasValue) + currentModePage = currentMode.Value.Pages[0]; + + if(dev.SCSIType == Decoders.SCSI.PeripheralDeviceTypes.MultiMediaDevice) + { + Decoders.SCSI.Modes.ModePage_01_MMC pgMMC = new Decoders.SCSI.Modes.ModePage_01_MMC(); + pgMMC.PS = false; + pgMMC.ReadRetryCount = 255; + pgMMC.Parameter = 0x20; + + Decoders.SCSI.Modes.DecodedMode md = new Decoders.SCSI.Modes.DecodedMode(); + md.Header = new Decoders.SCSI.Modes.ModeHeader(); + md.Pages = new Decoders.SCSI.Modes.ModePage[1]; + md.Pages[0] = new Decoders.SCSI.Modes.ModePage(); + md.Pages[0].Page = 0x01; + md.Pages[0].Subpage = 0x00; + md.Pages[0].PageResponse = Decoders.SCSI.Modes.EncodeModePage_01_MMC(pgMMC); + md6 = Decoders.SCSI.Modes.EncodeMode6(md, dev.SCSIType); + md10 = Decoders.SCSI.Modes.EncodeMode10(md, dev.SCSIType); + } + else + { + Decoders.SCSI.Modes.ModePage_01 pg = new Decoders.SCSI.Modes.ModePage_01(); + pg.PS = false; + pg.AWRE = false; + pg.ARRE = false; + pg.TB = true; + pg.RC = false; + pg.EER = true; + pg.PER = false; + pg.DTE = false; + pg.DCR = false; + pg.ReadRetryCount = 255; + + Decoders.SCSI.Modes.DecodedMode md = new Decoders.SCSI.Modes.DecodedMode(); + md.Header = new Decoders.SCSI.Modes.ModeHeader(); + md.Pages = new Decoders.SCSI.Modes.ModePage[1]; + md.Pages[0] = new Decoders.SCSI.Modes.ModePage(); + md.Pages[0].Page = 0x01; + md.Pages[0].Subpage = 0x00; + md.Pages[0].PageResponse = Decoders.SCSI.Modes.EncodeModePage_01(pg); + md6 = Decoders.SCSI.Modes.EncodeMode6(md, dev.SCSIType); + md10 = Decoders.SCSI.Modes.EncodeMode10(md, dev.SCSIType); + } + + sense = dev.ModeSelect(md6, out senseBuf, true, false, dev.Timeout, out duration); + if(sense) + { + sense = dev.ModeSelect10(md10, out senseBuf, true, false, dev.Timeout, out duration); + } + + runningPersistent = true; + if(!sense && !dev.Error) + { + pass--; + goto repeatRetry; + } + } + else if(runningPersistent && persistent && currentModePage.HasValue) + { + Decoders.SCSI.Modes.DecodedMode md = new Decoders.SCSI.Modes.DecodedMode(); + md.Header = new Decoders.SCSI.Modes.ModeHeader(); + md.Pages = new Decoders.SCSI.Modes.ModePage[1]; + md.Pages[0] = currentModePage.Value; + md6 = Decoders.SCSI.Modes.EncodeMode6(md, dev.SCSIType); + md10 = Decoders.SCSI.Modes.EncodeMode10(md, dev.SCSIType); + + sense = dev.ModeSelect(md6, out senseBuf, true, false, dev.Timeout, out duration); + if(sense) + { + sense = dev.ModeSelect10(md10, out senseBuf, true, false, dev.Timeout, out duration); + } + } + + DicConsole.WriteLine(); + } + #endregion Error handling + + dataChk = new Checksum(); + dumpFile.Seek(0, SeekOrigin.Begin); + blocksToRead = 500; + + blocks = totalSize; + + for(ulong i = 0; i < blocks; i += blocksToRead) + { + if(aborted) + break; + + if((blocks - i) < blocksToRead) + blocksToRead = (uint)(blocks - i); + + DicConsole.Write("\rChecksumming sector {0} of {1} ({2:F3} MiB/sec.)", i, blocks, currentSpeed); + + DateTime chkStart = DateTime.UtcNow; + byte[] dataToCheck = new byte[blockSize * blocksToRead]; + dumpFile.Read(dataToCheck, 0, (int)(blockSize * blocksToRead)); + dataChk.Update(dataToCheck); + DateTime chkEnd = DateTime.UtcNow; + + double chkDuration = (chkEnd - chkStart).TotalMilliseconds; + totalChkDuration += chkDuration; + +#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created + currentSpeed = ((double)blockSize * blocksToRead / (double)1048576) / (chkDuration / (double)1000); +#pragma warning restore IDE0004 // Cast is necessary, otherwise incorrect value is created + } + DicConsole.WriteLine(); + dumpFile.Close(); + end = DateTime.UtcNow; + + PluginBase plugins = new PluginBase(); + plugins.RegisterAllPlugins(); + ImagePlugin _imageFormat; + FiltersList filtersList = new FiltersList(); + Filter inputFilter = filtersList.GetFilter(outputPrefix + ".bin"); + + if(inputFilter == null) + { + DicConsole.ErrorWriteLine("Cannot open file just created, this should not happen."); + return; + } + + _imageFormat = ImageFormat.Detect(inputFilter); + PartitionType[] xmlFileSysInfo = null; + + try + { + if(!_imageFormat.OpenImage(inputFilter)) + _imageFormat = null; + } + catch + { + _imageFormat = null; + } + + if(_imageFormat != null) + { + List partitions = new List(); + + foreach(PartPlugin _partplugin in plugins.PartPluginsList.Values) + { + List _partitions; + + if(_partplugin.GetInformation(_imageFormat, out _partitions)) + { + partitions.AddRange(_partitions); + Statistics.AddPartition(_partplugin.Name); + } + } + + if(partitions.Count > 0) + { + xmlFileSysInfo = new PartitionType[partitions.Count]; + for(int i = 0; i < partitions.Count; i++) + { + xmlFileSysInfo[i] = new PartitionType(); + xmlFileSysInfo[i].Description = partitions[i].PartitionDescription; + xmlFileSysInfo[i].EndSector = (int)(partitions[i].PartitionStartSector + partitions[i].PartitionSectors - 1); + xmlFileSysInfo[i].Name = partitions[i].PartitionName; + xmlFileSysInfo[i].Sequence = (int)partitions[i].PartitionSequence; + xmlFileSysInfo[i].StartSector = (int)partitions[i].PartitionStartSector; + xmlFileSysInfo[i].Type = partitions[i].PartitionType; + + List lstFs = new List(); + + foreach(Filesystem _plugin in plugins.PluginsList.Values) + { + try + { + if(_plugin.Identify(_imageFormat, partitions[i].PartitionStartSector, partitions[i].PartitionStartSector + partitions[i].PartitionSectors - 1)) + { + string foo; + _plugin.GetInformation(_imageFormat, partitions[i].PartitionStartSector, partitions[i].PartitionStartSector + partitions[i].PartitionSectors - 1, out foo); + lstFs.Add(_plugin.XmlFSType); + Statistics.AddFilesystem(_plugin.XmlFSType.Type); + + if(_plugin.XmlFSType.Type == "Opera") + dskType = MediaType.ThreeDO; + if(_plugin.XmlFSType.Type == "PC Engine filesystem") + dskType = MediaType.SuperCDROM2; + if(_plugin.XmlFSType.Type == "Nintendo Wii filesystem") + dskType = MediaType.WOD; + if(_plugin.XmlFSType.Type == "Nintendo Gamecube filesystem") + dskType = MediaType.GOD; + } + } +#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body + catch +#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body + { + //DicConsole.DebugWriteLine("Dump-media command", "Plugin {0} crashed", _plugin.Name); + } + } + + if(lstFs.Count > 0) + xmlFileSysInfo[i].FileSystems = lstFs.ToArray(); + } + } + else + { + xmlFileSysInfo = new PartitionType[1]; + xmlFileSysInfo[0] = new PartitionType(); + xmlFileSysInfo[0].EndSector = (int)(blocks - 1); + xmlFileSysInfo[0].StartSector = 0; + + List lstFs = new List(); + + foreach(Filesystem _plugin in plugins.PluginsList.Values) + { + try + { + if(_plugin.Identify(_imageFormat, (blocks - 1), 0)) + { + string foo; + _plugin.GetInformation(_imageFormat, (blocks - 1), 0, out foo); + lstFs.Add(_plugin.XmlFSType); + Statistics.AddFilesystem(_plugin.XmlFSType.Type); + + if(_plugin.XmlFSType.Type == "Opera") + dskType = MediaType.ThreeDO; + if(_plugin.XmlFSType.Type == "PC Engine filesystem") + dskType = MediaType.SuperCDROM2; + if(_plugin.XmlFSType.Type == "Nintendo Wii filesystem") + dskType = MediaType.WOD; + if(_plugin.XmlFSType.Type == "Nintendo Gamecube filesystem") + dskType = MediaType.GOD; + } + } +#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body + catch +#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body + { + //DicConsole.DebugWriteLine("Create-sidecar command", "Plugin {0} crashed", _plugin.Name); + } + } + + if(lstFs.Count > 0) + xmlFileSysInfo[0].FileSystems = lstFs.ToArray(); + } + } + + sidecar.OpticalDisc[0].Checksums = dataChk.End().ToArray(); + sidecar.OpticalDisc[0].DumpHardwareArray = new DumpHardwareType[1]; + sidecar.OpticalDisc[0].DumpHardwareArray[0] = new DumpHardwareType(); + sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents = new ExtentType[1]; + sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents[0] = new ExtentType(); + sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents[0].Start = 0; + sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents[0].End = (int)(blocks - 1); + sidecar.OpticalDisc[0].DumpHardwareArray[0].Manufacturer = dev.Manufacturer; + sidecar.OpticalDisc[0].DumpHardwareArray[0].Model = dev.Model; + sidecar.OpticalDisc[0].DumpHardwareArray[0].Revision = dev.Revision; + sidecar.OpticalDisc[0].DumpHardwareArray[0].Software = new SoftwareType(); + sidecar.OpticalDisc[0].DumpHardwareArray[0].Software.Name = "DiscImageChef"; + sidecar.OpticalDisc[0].DumpHardwareArray[0].Software.OperatingSystem = dev.PlatformID.ToString(); + sidecar.OpticalDisc[0].DumpHardwareArray[0].Software.Version = typeof(SCSI).Assembly.GetName().Version.ToString(); + sidecar.OpticalDisc[0].Image = new ImageType(); + sidecar.OpticalDisc[0].Image.format = "Raw disk image (sector by sector copy)"; + sidecar.OpticalDisc[0].Image.Value = outputPrefix + ".bin"; + sidecar.OpticalDisc[0].Layers = new LayersType(); + sidecar.OpticalDisc[0].Layers.type = LayersTypeType.OTP; + sidecar.OpticalDisc[0].Layers.typeSpecified = true; + sidecar.OpticalDisc[0].Layers.Sectors = new SectorsType[1]; + sidecar.OpticalDisc[0].Layers.Sectors[0] = new SectorsType(); + sidecar.OpticalDisc[0].Layers.Sectors[0].Value = (long)layerBreak; + sidecar.OpticalDisc[0].Sessions = 1; + sidecar.OpticalDisc[0].Tracks = new[] { 1 }; + sidecar.OpticalDisc[0].Track = new Schemas.TrackType[1]; + sidecar.OpticalDisc[0].Track[0] = new Schemas.TrackType(); + sidecar.OpticalDisc[0].Track[0].BytesPerSector = (int)blockSize; + sidecar.OpticalDisc[0].Track[0].Checksums = sidecar.OpticalDisc[0].Checksums; + sidecar.OpticalDisc[0].Track[0].EndSector = (long)(blocks - 1); + sidecar.OpticalDisc[0].Track[0].Image = new ImageType(); + sidecar.OpticalDisc[0].Track[0].Image.format = "BINARY"; + sidecar.OpticalDisc[0].Track[0].Image.offset = 0; + sidecar.OpticalDisc[0].Track[0].Image.offsetSpecified = true; + sidecar.OpticalDisc[0].Track[0].Image.Value = sidecar.OpticalDisc[0].Image.Value; + sidecar.OpticalDisc[0].Track[0].Sequence = new TrackSequenceType(); + sidecar.OpticalDisc[0].Track[0].Sequence.Session = 1; + sidecar.OpticalDisc[0].Track[0].Sequence.TrackNumber = 1; + sidecar.OpticalDisc[0].Track[0].Size = (long)(totalSize * blockSize); + sidecar.OpticalDisc[0].Track[0].StartSector = 0; + if(xmlFileSysInfo != null) + sidecar.OpticalDisc[0].Track[0].FileSystemInformation = xmlFileSysInfo; + sidecar.OpticalDisc[0].Track[0].TrackType1 = TrackTypeTrackType.dvd; + sidecar.OpticalDisc[0].Dimensions = Metadata.Dimensions.DimensionsFromMediaType(dskType); + string xmlDskTyp, xmlDskSubTyp; + Metadata.MediaType.MediaTypeToString(dskType, out xmlDskTyp, out xmlDskSubTyp); + sidecar.OpticalDisc[0].DiscType = xmlDskTyp; + sidecar.OpticalDisc[0].DiscSubType = xmlDskSubTyp; + } + #endregion Xbox Game Disc + else + { + uint longBlockSize = blockSize; + bool rawAble = false; + + if(dumpRaw) + { + bool testSense; + Decoders.SCSI.FixedSense? decSense; + + if(dev.SCSIType != Decoders.SCSI.PeripheralDeviceTypes.MultiMediaDevice) + { + /*testSense = dev.ReadLong16(out readBuffer, out senseBuf, false, 0, 0xFFFF, dev.Timeout, out duration); + if (testSense && !dev.Error) + { + decSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf); + if (decSense.HasValue) + { + if (decSense.Value.SenseKey == DiscImageChef.Decoders.SCSI.SenseKeys.IllegalRequest && + decSense.Value.ASC == 0x24 && decSense.Value.ASCQ == 0x00) + { + rawAble = true; + if (decSense.Value.InformationValid && decSense.Value.ILI) + { + longBlockSize = 0xFFFF - (decSense.Value.Information & 0xFFFF); + readLong16 = !dev.ReadLong16(out readBuffer, out senseBuf, false, 0, longBlockSize, dev.Timeout, out duration); + } + } + } + }*/ + + testSense = dev.ReadLong10(out readBuffer, out senseBuf, false, false, 0, 0xFFFF, dev.Timeout, out duration); + if(testSense && !dev.Error) + { + decSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf); + if(decSense.HasValue) + { + if(decSense.Value.SenseKey == Decoders.SCSI.SenseKeys.IllegalRequest && + decSense.Value.ASC == 0x24 && decSense.Value.ASCQ == 0x00) + { + rawAble = true; + if(decSense.Value.InformationValid && decSense.Value.ILI) + { + longBlockSize = 0xFFFF - (decSense.Value.Information & 0xFFFF); + readLong10 = !dev.ReadLong10(out readBuffer, out senseBuf, false, false, 0, (ushort)longBlockSize, dev.Timeout, out duration); + } + } + } + } + + if(rawAble && longBlockSize == blockSize) + { + if(blockSize == 512) + { + // Long sector sizes for 512-byte magneto-opticals + foreach(ushort testSize in new[] { 600, 610, 630 }) + { + testSense = dev.ReadLong16(out readBuffer, out senseBuf, false, 0, testSize, dev.Timeout, out duration); + if(!testSense && !dev.Error) + { + readLong16 = true; + longBlockSize = testSize; + rawAble = true; + break; + } + + testSense = dev.ReadLong10(out readBuffer, out senseBuf, false, false, 0, testSize, dev.Timeout, out duration); + if(!testSense && !dev.Error) + { + readLong10 = true; + longBlockSize = testSize; + rawAble = true; + break; + } + } + } + else if(blockSize == 1024) + { + testSense = dev.ReadLong16(out readBuffer, out senseBuf, false, 0, 1200, dev.Timeout, out duration); + if(!testSense && !dev.Error) + { + readLong16 = true; + longBlockSize = 1200; + rawAble = true; + } + else + { + testSense = dev.ReadLong10(out readBuffer, out senseBuf, false, false, 0, 1200, dev.Timeout, out duration); + if(!testSense && !dev.Error) + { + readLong10 = true; + longBlockSize = 1200; + rawAble = true; + } + } + } + else if(blockSize == 2048) + { + testSense = dev.ReadLong16(out readBuffer, out senseBuf, false, 0, 2380, dev.Timeout, out duration); + if(!testSense && !dev.Error) + { + readLong16 = true; + longBlockSize = 2380; + rawAble = true; + } + else + { + testSense = dev.ReadLong10(out readBuffer, out senseBuf, false, false, 0, 2380, dev.Timeout, out duration); + if(!testSense && !dev.Error) + { + readLong10 = true; + longBlockSize = 2380; + rawAble = true; + } + } + } + else if(blockSize == 4096) + { + testSense = dev.ReadLong16(out readBuffer, out senseBuf, false, 0, 4760, dev.Timeout, out duration); + if(!testSense && !dev.Error) + { + readLong16 = true; + longBlockSize = 4760; + rawAble = true; + } + else + { + testSense = dev.ReadLong10(out readBuffer, out senseBuf, false, false, 0, 4760, dev.Timeout, out duration); + if(!testSense && !dev.Error) + { + readLong10 = true; + longBlockSize = 4760; + rawAble = true; + } + } + } + else if(blockSize == 8192) + { + testSense = dev.ReadLong16(out readBuffer, out senseBuf, false, 0, 9424, dev.Timeout, out duration); + if(!testSense && !dev.Error) + { + readLong16 = true; + longBlockSize = 9424; + rawAble = true; + } + else + { + testSense = dev.ReadLong10(out readBuffer, out senseBuf, false, false, 0, 9424, dev.Timeout, out duration); + if(!testSense && !dev.Error) + { + readLong10 = true; + longBlockSize = 9424; + rawAble = true; + } + } + } + } + + if(!rawAble && dev.Manufacturer == "SYQUEST") + { + testSense = dev.SyQuestReadLong10(out readBuffer, out senseBuf, 0, 0xFFFF, dev.Timeout, out duration); + if(testSense) + { + decSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf); + if(decSense.HasValue) + { + if(decSense.Value.SenseKey == Decoders.SCSI.SenseKeys.IllegalRequest && + decSense.Value.ASC == 0x24 && decSense.Value.ASCQ == 0x00) + { + rawAble = true; + if(decSense.Value.InformationValid && decSense.Value.ILI) + { + longBlockSize = 0xFFFF - (decSense.Value.Information & 0xFFFF); + syqReadLong10 = !dev.SyQuestReadLong10(out readBuffer, out senseBuf, 0, longBlockSize, dev.Timeout, out duration); + } + } + else + { + testSense = dev.SyQuestReadLong6(out readBuffer, out senseBuf, 0, 0xFFFF, dev.Timeout, out duration); + if(testSense) + { + decSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf); + if(decSense.HasValue) + { + if(decSense.Value.SenseKey == Decoders.SCSI.SenseKeys.IllegalRequest && + decSense.Value.ASC == 0x24 && decSense.Value.ASCQ == 0x00) + { + rawAble = true; + if(decSense.Value.InformationValid && decSense.Value.ILI) + { + longBlockSize = 0xFFFF - (decSense.Value.Information & 0xFFFF); + syqReadLong6 = !dev.SyQuestReadLong6(out readBuffer, out senseBuf, 0, longBlockSize, dev.Timeout, out duration); + } + } + } + } + } + } + } + + if(!rawAble && blockSize == 256) + { + testSense = dev.SyQuestReadLong6(out readBuffer, out senseBuf, 0, 262, dev.Timeout, out duration); + if(!testSense && !dev.Error) + { + syqReadLong6 = true; + longBlockSize = 262; + rawAble = true; + } + } + } + } + else + { + if(dev.Manufacturer == "HL-DT-ST") + hldtstReadRaw = !dev.HlDtStReadRawDvd(out readBuffer, out senseBuf, 0, 1, dev.Timeout, out duration); + + if(dev.Manufacturer == "PLEXTOR") + hldtstReadRaw = !dev.PlextorReadRawDvd(out readBuffer, out senseBuf, 0, 1, dev.Timeout, out duration); + + if(hldtstReadRaw || plextorReadRaw) + { + rawAble = true; + longBlockSize = 2064; + } + + // READ LONG (10) for some DVD drives + if(!rawAble && dev.Manufacturer == "MATSHITA") + { + testSense = dev.ReadLong10(out readBuffer, out senseBuf, false, false, 0, 37856, dev.Timeout, out duration); + if(!testSense && !dev.Error) + { + readLongDvd = true; + longBlockSize = 37856; + rawAble = true; + } + } + } + + if(blockSize == longBlockSize) + { + if(!rawAble) + { + DicConsole.ErrorWriteLine("Device doesn't seem capable of reading raw data from media."); + } + else + { + DicConsole.ErrorWriteLine("Device is capable of reading raw data but I've been unable to guess correct sector size."); + } + + if(!force) + { + DicConsole.ErrorWriteLine("Not continuing. If you want to continue reading cooked data when raw is not available use the force option."); + // TODO: Exit more gracefully + return; + } + + DicConsole.ErrorWriteLine("Continuing dumping cooked data."); + dumpRaw = false; + } + else + { + if(readLong16) + DicConsole.WriteLine("Using SCSI READ LONG (16) command."); + else if(readLong10 || readLongDvd) + DicConsole.WriteLine("Using SCSI READ LONG (10) command."); + else if(syqReadLong10) + DicConsole.WriteLine("Using SyQuest READ LONG (10) command."); + else if(syqReadLong6) + DicConsole.WriteLine("Using SyQuest READ LONG (6) command."); + else if(hldtstReadRaw) + DicConsole.WriteLine("Using HL-DT-ST raw DVD reading."); + else if(plextorReadRaw) + DicConsole.WriteLine("Using Plextor raw DVD reading."); + else + throw new AccessViolationException("Should not arrive here"); + + if(readLongDvd) // Only a block will be read, but it contains 16 sectors and command expect sector number not block number + blocksToRead = 16; + else + blocksToRead = 1; + DicConsole.WriteLine("Reading {0} raw bytes ({1} cooked bytes) per sector.", + longBlockSize, blockSize * blocksToRead); + physicalBlockSize = longBlockSize; + blockSize = longBlockSize; + } + } + + if(!dumpRaw) + { + read6 = !dev.Read6(out readBuffer, out senseBuf, 0, blockSize, dev.Timeout, out duration); + + read10 = !dev.Read10(out readBuffer, out senseBuf, 0, false, true, false, false, 0, blockSize, 0, 1, dev.Timeout, out duration); + + read12 = !dev.Read12(out readBuffer, out senseBuf, 0, false, true, false, false, 0, blockSize, 0, 1, false, dev.Timeout, out duration); + + read16 = !dev.Read16(out readBuffer, out senseBuf, 0, false, true, false, 0, blockSize, 0, 1, false, dev.Timeout, out duration); + + if(!read6 && !read10 && !read12 && !read16) + { + DicConsole.ErrorWriteLine("Cannot read medium, aborting scan..."); + return; + } + + if(read6 && !read10 && !read12 && !read16 && blocks > (0x001FFFFF + 1)) + { + DicConsole.ErrorWriteLine("Device only supports SCSI READ (6) but has more than {0} blocks ({1} blocks total)", 0x001FFFFF + 1, blocks); + return; + } + +#pragma warning disable IDE0004 // Remove Unnecessary Cast + if(!read16 && blocks > ((long)0xFFFFFFFF + (long)1)) +#pragma warning restore IDE0004 // Remove Unnecessary Cast + { +#pragma warning disable IDE0004 // Remove Unnecessary Cast + DicConsole.ErrorWriteLine("Device only supports SCSI READ (10) but has more than {0} blocks ({1} blocks total)", (long)0xFFFFFFFF + (long)1, blocks); +#pragma warning restore IDE0004 // Remove Unnecessary Cast + return; + } + + if(read16) + DicConsole.WriteLine("Using SCSI READ (16) command."); + else if(read12) + DicConsole.WriteLine("Using SCSI READ (12) command."); + else if(read10) + DicConsole.WriteLine("Using SCSI READ (10) command."); + else if(read6) + DicConsole.WriteLine("Using SCSI READ (6) command."); + + while(true) + { + if(read16) + { + sense = dev.Read16(out readBuffer, out senseBuf, 0, false, true, false, 0, blockSize, 0, blocksToRead, false, dev.Timeout, out duration); + if(dev.Error) + blocksToRead /= 2; + } + else if(read12) + { + sense = dev.Read12(out readBuffer, out senseBuf, 0, false, false, false, false, 0, blockSize, 0, blocksToRead, false, dev.Timeout, out duration); + if(dev.Error) + blocksToRead /= 2; + } + else if(read10) + { + sense = dev.Read10(out readBuffer, out senseBuf, 0, false, true, false, false, 0, blockSize, 0, (ushort)blocksToRead, dev.Timeout, out duration); + if(dev.Error) + blocksToRead /= 2; + } + else if(read6) + { + sense = dev.Read6(out readBuffer, out senseBuf, 0, blockSize, (byte)blocksToRead, dev.Timeout, out duration); + if(dev.Error) + blocksToRead /= 2; + } + + if(!dev.Error || blocksToRead == 1) + break; + } + + if(dev.Error) + { + DicConsole.ErrorWriteLine("Device error {0} trying to guess ideal transfer length.", dev.LastError); + return; + } + } + + DicConsole.WriteLine("Reading {0} sectors at a time.", blocksToRead); + + mhddLog = new MHDDLog(outputPrefix + ".mhddlog.bin", dev, blocks, blockSize, blocksToRead); + ibgLog = new IBGLog(outputPrefix + ".ibg", currentProfile); + dumpFile = new DataFile(outputPrefix + ".bin"); + + start = DateTime.UtcNow; + + readBuffer = null; + + for(ulong i = 0; i < blocks; i += blocksToRead) + { + if(aborted) + break; + + double cmdDuration = 0; + + if((blocks - i) < blocksToRead) + blocksToRead = (uint)(blocks - i); + +#pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator + if(currentSpeed > maxSpeed && currentSpeed != 0) + maxSpeed = currentSpeed; + if(currentSpeed < minSpeed && currentSpeed != 0) + minSpeed = currentSpeed; +#pragma warning restore RECS0018 // Comparison of floating point numbers with equality operator + + DicConsole.Write("\rReading sector {0} of {1} ({2:F3} MiB/sec.)", i, blocks, currentSpeed); + + if(readLong16) + { + sense = dev.ReadLong16(out readBuffer, out senseBuf, false, i, blockSize, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + else if(readLong10 || readLongDvd) + { + sense = dev.ReadLong10(out readBuffer, out senseBuf, false, false, (uint)i, (ushort)blockSize, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + else if(syqReadLong10) + { + sense = dev.SyQuestReadLong10(out readBuffer, out senseBuf, (uint)i, blockSize, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + else if(syqReadLong6) + { + sense = dev.SyQuestReadLong6(out readBuffer, out senseBuf, (uint)i, blockSize, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + else if(hldtstReadRaw) + { + sense = dev.HlDtStReadRawDvd(out readBuffer, out senseBuf, (uint)i, blockSize, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + else if(plextorReadRaw) + { + sense = dev.PlextorReadRawDvd(out readBuffer, out senseBuf, (uint)i, blockSize, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + else if(read16) + { + sense = dev.Read16(out readBuffer, out senseBuf, 0, false, true, false, i, blockSize, 0, blocksToRead, false, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + else if(read12) + { + sense = dev.Read12(out readBuffer, out senseBuf, 0, false, false, false, false, (uint)i, blockSize, 0, blocksToRead, false, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + else if(read10) + { + sense = dev.Read10(out readBuffer, out senseBuf, 0, false, true, false, false, (uint)i, blockSize, 0, (ushort)blocksToRead, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + else if(read6) + { + sense = dev.Read6(out readBuffer, out senseBuf, (uint)i, blockSize, (byte)blocksToRead, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + + if(!sense && !dev.Error) + { + mhddLog.Write(i, cmdDuration); + ibgLog.Write(i, currentSpeed * 1024); + dumpFile.Write(readBuffer); + } + else + { + // TODO: Reset device after X errors + if(stopOnError) + return; // TODO: Return more cleanly + + // Write empty data + dumpFile.Write(new byte[blockSize * blocksToRead]); + + // TODO: Record error on mapfile + + errored += blocksToRead; + unreadableSectors.Add(i); + DicConsole.DebugWriteLine("Dump-Media", "READ error:\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); + if(cmdDuration < 500) + mhddLog.Write(i, 65535); + else + mhddLog.Write(i, cmdDuration); + + ibgLog.Write(i, 0); + } + +#pragma warning disable IDE0004 // Remove Unnecessary Cast + currentSpeed = ((double)blockSize * blocksToRead / (double)1048576) / (cmdDuration / (double)1000); +#pragma warning restore IDE0004 // Remove Unnecessary Cast + } + end = DateTime.UtcNow; + DicConsole.WriteLine(); + mhddLog.Close(); +#pragma warning disable IDE0004 // Remove Unnecessary Cast + ibgLog.Close(dev, blocks, blockSize, (end - start).TotalSeconds, currentSpeed * 1024, (((double)blockSize * (double)(blocks + 1)) / 1024) / (totalDuration / 1000), devicePath); +#pragma warning restore IDE0004 // Remove Unnecessary Cast + + #region Error handling + if(unreadableSectors.Count > 0 && !aborted) + { + List tmpList = new List(); + + foreach(ulong ur in unreadableSectors) + { + for(ulong i = ur; i < ur + blocksToRead; i++) + tmpList.Add(i); + } + + tmpList.Sort(); + + int pass = 0; + bool forward = true; + bool runningPersistent = false; + + unreadableSectors = tmpList; + + repeatRetry: + ulong[] tmpArray = unreadableSectors.ToArray(); + foreach(ulong badSector in tmpArray) + { + if(aborted) + break; + + double cmdDuration = 0; + + DicConsole.Write("\rRetrying sector {0}, pass {1}, {3}{2}", badSector, pass + 1, forward ? "forward" : "reverse", runningPersistent ? "recovering partial data, " : ""); + + if(readLong16) + { + sense = dev.ReadLong16(out readBuffer, out senseBuf, false, badSector, blockSize, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + else if(readLong10) + { + sense = dev.ReadLong10(out readBuffer, out senseBuf, false, false, (uint)badSector, (ushort)blockSize, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + else if(syqReadLong10) + { + sense = dev.SyQuestReadLong10(out readBuffer, out senseBuf, (uint)badSector, blockSize, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + else if(syqReadLong6) + { + sense = dev.SyQuestReadLong6(out readBuffer, out senseBuf, (uint)badSector, blockSize, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + else if(hldtstReadRaw) + { + sense = dev.HlDtStReadRawDvd(out readBuffer, out senseBuf, (uint)badSector, blockSize, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + else if(plextorReadRaw) + { + sense = dev.PlextorReadRawDvd(out readBuffer, out senseBuf, (uint)badSector, blockSize, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + else if(read16) + { + sense = dev.Read16(out readBuffer, out senseBuf, 0, false, true, false, badSector, blockSize, 0, 1, false, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + else if(read12) + { + sense = dev.Read12(out readBuffer, out senseBuf, 0, false, false, false, false, (uint)badSector, blockSize, 0, 1, false, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + else if(read10) + { + sense = dev.Read10(out readBuffer, out senseBuf, 0, false, true, false, false, (uint)badSector, blockSize, 0, 1, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + else if(read6) + { + sense = dev.Read6(out readBuffer, out senseBuf, (uint)badSector, blockSize, 1, dev.Timeout, out cmdDuration); + totalDuration += cmdDuration; + } + + if(!sense && !dev.Error) + { + unreadableSectors.Remove(badSector); + dumpFile.WriteAt(readBuffer, badSector, blockSize); + } + else if(runningPersistent) + dumpFile.WriteAt(readBuffer, badSector, blockSize); + } + + if(pass < retryPasses && !aborted && unreadableSectors.Count > 0) + { + pass++; + forward = !forward; + unreadableSectors.Sort(); + unreadableSectors.Reverse(); + goto repeatRetry; + } + + Decoders.SCSI.Modes.DecodedMode? currentMode = null; + Decoders.SCSI.Modes.ModePage? currentModePage = null; + byte[] md6 = null; + byte[] md10 = null; + + if(!runningPersistent && persistent) + { + sense = dev.ModeSense6(out readBuffer, out senseBuf, false, ScsiModeSensePageControl.Current, 0x01, dev.Timeout, out duration); + if(sense) + { + sense = dev.ModeSense10(out readBuffer, out senseBuf, false, ScsiModeSensePageControl.Current, 0x01, dev.Timeout, out duration); + if(!sense) + currentMode = Decoders.SCSI.Modes.DecodeMode10(readBuffer, dev.SCSIType); + } + else + currentMode = Decoders.SCSI.Modes.DecodeMode6(readBuffer, dev.SCSIType); + + if(currentMode.HasValue) + currentModePage = currentMode.Value.Pages[0]; + + if(dev.SCSIType == Decoders.SCSI.PeripheralDeviceTypes.MultiMediaDevice) + { + Decoders.SCSI.Modes.ModePage_01_MMC pgMMC = new Decoders.SCSI.Modes.ModePage_01_MMC(); + pgMMC.PS = false; + pgMMC.ReadRetryCount = 255; + pgMMC.Parameter = 0x20; + + Decoders.SCSI.Modes.DecodedMode md = new Decoders.SCSI.Modes.DecodedMode(); + md.Header = new Decoders.SCSI.Modes.ModeHeader(); + md.Pages = new Decoders.SCSI.Modes.ModePage[1]; + md.Pages[0] = new Decoders.SCSI.Modes.ModePage(); + md.Pages[0].Page = 0x01; + md.Pages[0].Subpage = 0x00; + md.Pages[0].PageResponse = Decoders.SCSI.Modes.EncodeModePage_01_MMC(pgMMC); + md6 = Decoders.SCSI.Modes.EncodeMode6(md, dev.SCSIType); + md10 = Decoders.SCSI.Modes.EncodeMode10(md, dev.SCSIType); + } + else + { + Decoders.SCSI.Modes.ModePage_01 pg = new Decoders.SCSI.Modes.ModePage_01(); + pg.PS = false; + pg.AWRE = false; + pg.ARRE = false; + pg.TB = true; + pg.RC = false; + pg.EER = true; + pg.PER = false; + pg.DTE = false; + pg.DCR = false; + pg.ReadRetryCount = 255; + + Decoders.SCSI.Modes.DecodedMode md = new Decoders.SCSI.Modes.DecodedMode(); + md.Header = new Decoders.SCSI.Modes.ModeHeader(); + md.Pages = new Decoders.SCSI.Modes.ModePage[1]; + md.Pages[0] = new Decoders.SCSI.Modes.ModePage(); + md.Pages[0].Page = 0x01; + md.Pages[0].Subpage = 0x00; + md.Pages[0].PageResponse = Decoders.SCSI.Modes.EncodeModePage_01(pg); + md6 = Decoders.SCSI.Modes.EncodeMode6(md, dev.SCSIType); + md10 = Decoders.SCSI.Modes.EncodeMode10(md, dev.SCSIType); + } + + sense = dev.ModeSelect(md6, out senseBuf, true, false, dev.Timeout, out duration); + if(sense) + { + sense = dev.ModeSelect10(md10, out senseBuf, true, false, dev.Timeout, out duration); + } + + runningPersistent = true; + if(!sense && !dev.Error) + { + pass--; + goto repeatRetry; + } + } + else if(runningPersistent && persistent && currentModePage.HasValue) + { + Decoders.SCSI.Modes.DecodedMode md = new Decoders.SCSI.Modes.DecodedMode(); + md.Header = new Decoders.SCSI.Modes.ModeHeader(); + md.Pages = new Decoders.SCSI.Modes.ModePage[1]; + md.Pages[0] = currentModePage.Value; + md6 = Decoders.SCSI.Modes.EncodeMode6(md, dev.SCSIType); + md10 = Decoders.SCSI.Modes.EncodeMode10(md, dev.SCSIType); + + sense = dev.ModeSelect(md6, out senseBuf, true, false, dev.Timeout, out duration); + if(sense) + { + sense = dev.ModeSelect10(md10, out senseBuf, true, false, dev.Timeout, out duration); + } + } + + DicConsole.WriteLine(); + } + #endregion Error handling + + dataChk = new Checksum(); + dumpFile.Seek(0, SeekOrigin.Begin); + blocksToRead = 500; + + for(ulong i = 0; i < blocks; i += blocksToRead) + { + if(aborted) + break; + + if((blocks - i) < blocksToRead) + blocksToRead = (uint)(blocks - i); + + DicConsole.Write("\rChecksumming sector {0} of {1} ({2:F3} MiB/sec.)", i, blocks, currentSpeed); + + DateTime chkStart = DateTime.UtcNow; + byte[] dataToCheck = new byte[blockSize * blocksToRead]; + dumpFile.Read(dataToCheck, 0, (int)(blockSize * blocksToRead)); + dataChk.Update(dataToCheck); + DateTime chkEnd = DateTime.UtcNow; + + double chkDuration = (chkEnd - chkStart).TotalMilliseconds; + totalChkDuration += chkDuration; + +#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created + currentSpeed = ((double)blockSize * blocksToRead / (double)1048576) / (chkDuration / (double)1000); +#pragma warning restore IDE0004 // Cast is necessary, otherwise incorrect value is created + } + DicConsole.WriteLine(); + dumpFile.Close(); + end = DateTime.UtcNow; + + PluginBase plugins = new PluginBase(); + plugins.RegisterAllPlugins(); + ImagePlugin _imageFormat; + FiltersList filtersList = new FiltersList(); + Filter inputFilter = filtersList.GetFilter(outputPrefix + ".bin"); + + if(inputFilter == null) + { + DicConsole.ErrorWriteLine("Cannot open file just created, this should not happen."); + return; + } + + _imageFormat = ImageFormat.Detect(inputFilter); + PartitionType[] xmlFileSysInfo = null; + + try + { + if(!_imageFormat.OpenImage(inputFilter)) + _imageFormat = null; + } + catch + { + _imageFormat = null; + } + + if(_imageFormat != null) + { + List partitions = new List(); + + foreach(PartPlugin _partplugin in plugins.PartPluginsList.Values) + { + List _partitions; + + if(_partplugin.GetInformation(_imageFormat, out _partitions)) + { + partitions.AddRange(_partitions); + Statistics.AddPartition(_partplugin.Name); + } + } + + if(partitions.Count > 0) + { + xmlFileSysInfo = new PartitionType[partitions.Count]; + for(int i = 0; i < partitions.Count; i++) + { + xmlFileSysInfo[i] = new PartitionType(); + xmlFileSysInfo[i].Description = partitions[i].PartitionDescription; + xmlFileSysInfo[i].EndSector = (int)(partitions[i].PartitionStartSector + partitions[i].PartitionSectors - 1); + xmlFileSysInfo[i].Name = partitions[i].PartitionName; + xmlFileSysInfo[i].Sequence = (int)partitions[i].PartitionSequence; + xmlFileSysInfo[i].StartSector = (int)partitions[i].PartitionStartSector; + xmlFileSysInfo[i].Type = partitions[i].PartitionType; + + List lstFs = new List(); + + foreach(Filesystem _plugin in plugins.PluginsList.Values) + { + try + { + if(_plugin.Identify(_imageFormat, partitions[i].PartitionStartSector, partitions[i].PartitionStartSector + partitions[i].PartitionSectors - 1)) + { + string foo; + _plugin.GetInformation(_imageFormat, partitions[i].PartitionStartSector, partitions[i].PartitionStartSector + partitions[i].PartitionSectors - 1, out foo); + lstFs.Add(_plugin.XmlFSType); + Statistics.AddFilesystem(_plugin.XmlFSType.Type); + + if(_plugin.XmlFSType.Type == "Opera") + dskType = MediaType.ThreeDO; + if(_plugin.XmlFSType.Type == "PC Engine filesystem") + dskType = MediaType.SuperCDROM2; + if(_plugin.XmlFSType.Type == "Nintendo Wii filesystem") + dskType = MediaType.WOD; + if(_plugin.XmlFSType.Type == "Nintendo Gamecube filesystem") + dskType = MediaType.GOD; + } + } +#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body + catch +#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body + { + //DicConsole.DebugWriteLine("Dump-media command", "Plugin {0} crashed", _plugin.Name); + } + } + + if(lstFs.Count > 0) + xmlFileSysInfo[i].FileSystems = lstFs.ToArray(); + } + } + else + { + xmlFileSysInfo = new PartitionType[1]; + xmlFileSysInfo[0] = new PartitionType(); + xmlFileSysInfo[0].EndSector = (int)(blocks - 1); + xmlFileSysInfo[0].StartSector = 0; + + List lstFs = new List(); + + foreach(Filesystem _plugin in plugins.PluginsList.Values) + { + try + { + if(_plugin.Identify(_imageFormat, (blocks - 1), 0)) + { + string foo; + _plugin.GetInformation(_imageFormat, (blocks - 1), 0, out foo); + lstFs.Add(_plugin.XmlFSType); + Statistics.AddFilesystem(_plugin.XmlFSType.Type); + + if(_plugin.XmlFSType.Type == "Opera") + dskType = MediaType.ThreeDO; + if(_plugin.XmlFSType.Type == "PC Engine filesystem") + dskType = MediaType.SuperCDROM2; + if(_plugin.XmlFSType.Type == "Nintendo Wii filesystem") + dskType = MediaType.WOD; + if(_plugin.XmlFSType.Type == "Nintendo Gamecube filesystem") + dskType = MediaType.GOD; + } + } +#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body + catch +#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body + { + //DicConsole.DebugWriteLine("Create-sidecar command", "Plugin {0} crashed", _plugin.Name); + } + } + + if(lstFs.Count > 0) + xmlFileSysInfo[0].FileSystems = lstFs.ToArray(); + } + } + + if(opticalDisc) + { + sidecar.OpticalDisc[0].Checksums = dataChk.End().ToArray(); + sidecar.OpticalDisc[0].DumpHardwareArray = new DumpHardwareType[1]; + sidecar.OpticalDisc[0].DumpHardwareArray[0] = new DumpHardwareType(); + sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents = new ExtentType[1]; + sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents[0] = new ExtentType(); + sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents[0].Start = 0; + sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents[0].End = (int)(blocks - 1); + sidecar.OpticalDisc[0].DumpHardwareArray[0].Manufacturer = dev.Manufacturer; + sidecar.OpticalDisc[0].DumpHardwareArray[0].Model = dev.Model; + sidecar.OpticalDisc[0].DumpHardwareArray[0].Revision = dev.Revision; + sidecar.OpticalDisc[0].DumpHardwareArray[0].Software = new SoftwareType(); + sidecar.OpticalDisc[0].DumpHardwareArray[0].Software.Name = "DiscImageChef"; + sidecar.OpticalDisc[0].DumpHardwareArray[0].Software.OperatingSystem = dev.PlatformID.ToString(); + sidecar.OpticalDisc[0].DumpHardwareArray[0].Software.Version = typeof(SCSI).Assembly.GetName().Version.ToString(); + sidecar.OpticalDisc[0].Image = new ImageType(); + sidecar.OpticalDisc[0].Image.format = "Raw disk image (sector by sector copy)"; + sidecar.OpticalDisc[0].Image.Value = outputPrefix + ".bin"; + // TODO: Implement layers + //sidecar.OpticalDisc[0].Layers = new LayersType(); + sidecar.OpticalDisc[0].Sessions = 1; + sidecar.OpticalDisc[0].Tracks = new[] { 1 }; + sidecar.OpticalDisc[0].Track = new Schemas.TrackType[1]; + sidecar.OpticalDisc[0].Track[0] = new Schemas.TrackType(); + sidecar.OpticalDisc[0].Track[0].BytesPerSector = (int)blockSize; + sidecar.OpticalDisc[0].Track[0].Checksums = sidecar.OpticalDisc[0].Checksums; + sidecar.OpticalDisc[0].Track[0].EndSector = (long)(blocks - 1); + sidecar.OpticalDisc[0].Track[0].Image = new ImageType(); + sidecar.OpticalDisc[0].Track[0].Image.format = "BINARY"; + sidecar.OpticalDisc[0].Track[0].Image.offset = 0; + sidecar.OpticalDisc[0].Track[0].Image.offsetSpecified = true; + sidecar.OpticalDisc[0].Track[0].Image.Value = sidecar.OpticalDisc[0].Image.Value; + sidecar.OpticalDisc[0].Track[0].Sequence = new TrackSequenceType(); + sidecar.OpticalDisc[0].Track[0].Sequence.Session = 1; + sidecar.OpticalDisc[0].Track[0].Sequence.TrackNumber = 1; + sidecar.OpticalDisc[0].Track[0].Size = (long)(blocks * blockSize); + sidecar.OpticalDisc[0].Track[0].StartSector = 0; + if(xmlFileSysInfo != null) + sidecar.OpticalDisc[0].Track[0].FileSystemInformation = xmlFileSysInfo; + switch(dskType) + { + case MediaType.DDCD: + case MediaType.DDCDR: + case MediaType.DDCDRW: + sidecar.OpticalDisc[0].Track[0].TrackType1 = TrackTypeTrackType.ddcd; + break; + case MediaType.DVDROM: + case MediaType.DVDR: + case MediaType.DVDRAM: + case MediaType.DVDRW: + case MediaType.DVDRDL: + case MediaType.DVDRWDL: + case MediaType.DVDDownload: + case MediaType.DVDPRW: + case MediaType.DVDPR: + case MediaType.DVDPRWDL: + case MediaType.DVDPRDL: + sidecar.OpticalDisc[0].Track[0].TrackType1 = TrackTypeTrackType.dvd; + break; + case MediaType.HDDVDROM: + case MediaType.HDDVDR: + case MediaType.HDDVDRAM: + case MediaType.HDDVDRW: + case MediaType.HDDVDRDL: + case MediaType.HDDVDRWDL: + sidecar.OpticalDisc[0].Track[0].TrackType1 = TrackTypeTrackType.hddvd; + break; + case MediaType.BDROM: + case MediaType.BDR: + case MediaType.BDRE: + case MediaType.BDREXL: + case MediaType.BDRXL: + sidecar.OpticalDisc[0].Track[0].TrackType1 = TrackTypeTrackType.bluray; + break; + } + sidecar.OpticalDisc[0].Dimensions = Metadata.Dimensions.DimensionsFromMediaType(dskType); + string xmlDskTyp, xmlDskSubTyp; + Metadata.MediaType.MediaTypeToString(dskType, out xmlDskTyp, out xmlDskSubTyp); + sidecar.OpticalDisc[0].DiscType = xmlDskTyp; + sidecar.OpticalDisc[0].DiscSubType = xmlDskSubTyp; + } + else + { + sidecar.BlockMedia[0].Checksums = dataChk.End().ToArray(); + sidecar.BlockMedia[0].Dimensions = Metadata.Dimensions.DimensionsFromMediaType(dskType); + string xmlDskTyp, xmlDskSubTyp; + Metadata.MediaType.MediaTypeToString(dskType, out xmlDskTyp, out xmlDskSubTyp); + sidecar.BlockMedia[0].DiskType = xmlDskTyp; + sidecar.BlockMedia[0].DiskSubType = xmlDskSubTyp; + // TODO: Implement device firmware revision + sidecar.BlockMedia[0].Image = new ImageType(); + sidecar.BlockMedia[0].Image.format = "Raw disk image (sector by sector copy)"; + sidecar.BlockMedia[0].Image.Value = outputPrefix + ".bin"; + if(!dev.IsRemovable || dev.IsUSB) + { + if(dev.Type == DeviceType.ATAPI) + sidecar.BlockMedia[0].Interface = "ATAPI"; + else if(dev.IsUSB) + sidecar.BlockMedia[0].Interface = "USB"; + else if(dev.IsFireWire) + sidecar.BlockMedia[0].Interface = "FireWire"; + else + sidecar.BlockMedia[0].Interface = "SCSI"; + } + sidecar.BlockMedia[0].LogicalBlocks = (long)blocks; + sidecar.BlockMedia[0].PhysicalBlockSize = (int)physicalBlockSize; + sidecar.BlockMedia[0].LogicalBlockSize = (int)logicalBlockSize; + sidecar.BlockMedia[0].Manufacturer = dev.Manufacturer; + sidecar.BlockMedia[0].Model = dev.Model; + sidecar.BlockMedia[0].Serial = dev.Serial; + sidecar.BlockMedia[0].Size = (long)(blocks * blockSize); + if(xmlFileSysInfo != null) + sidecar.BlockMedia[0].FileSystemInformation = xmlFileSysInfo; + + if(dev.IsRemovable) + { + sidecar.BlockMedia[0].DumpHardwareArray = new DumpHardwareType[1]; + sidecar.BlockMedia[0].DumpHardwareArray[0] = new DumpHardwareType(); + sidecar.BlockMedia[0].DumpHardwareArray[0].Extents = new ExtentType[1]; + sidecar.BlockMedia[0].DumpHardwareArray[0].Extents[0] = new ExtentType(); + sidecar.BlockMedia[0].DumpHardwareArray[0].Extents[0].Start = 0; + sidecar.BlockMedia[0].DumpHardwareArray[0].Extents[0].End = (int)(blocks - 1); + sidecar.BlockMedia[0].DumpHardwareArray[0].Manufacturer = dev.Manufacturer; + sidecar.BlockMedia[0].DumpHardwareArray[0].Model = dev.Model; + sidecar.BlockMedia[0].DumpHardwareArray[0].Revision = dev.Revision; + sidecar.BlockMedia[0].DumpHardwareArray[0].Software = new SoftwareType(); + sidecar.BlockMedia[0].DumpHardwareArray[0].Software.Name = "DiscImageChef"; + sidecar.BlockMedia[0].DumpHardwareArray[0].Software.OperatingSystem = dev.PlatformID.ToString(); + sidecar.BlockMedia[0].DumpHardwareArray[0].Software.Version = typeof(SCSI).Assembly.GetName().Version.ToString(); + } + } + } + + DicConsole.WriteLine(); + + DicConsole.WriteLine("Took a total of {0:F3} seconds ({1:F3} processing commands, {2:F3} checksumming).", (end - start).TotalSeconds, totalDuration / 1000, totalChkDuration / 1000); +#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created + DicConsole.WriteLine("Avegare speed: {0:F3} MiB/sec.", (((double)blockSize * (double)(blocks + 1)) / 1048576) / (totalDuration / 1000)); +#pragma warning restore IDE0004 // Cast is necessary, otherwise incorrect value is created + DicConsole.WriteLine("Fastest speed burst: {0:F3} MiB/sec.", maxSpeed); + DicConsole.WriteLine("Slowest speed burst: {0:F3} MiB/sec.", minSpeed); + DicConsole.WriteLine("{0} sectors could not be read.", unreadableSectors.Count); + if(unreadableSectors.Count > 0) + { + unreadableSectors.Sort(); + foreach(ulong bad in unreadableSectors) + DicConsole.WriteLine("Sector {0} could not be read", bad); + } + DicConsole.WriteLine(); + + if(!aborted) + { + DicConsole.WriteLine("Writing metadata sidecar"); + + FileStream xmlFs = new FileStream(outputPrefix + ".cicm.xml", + FileMode.Create); + + System.Xml.Serialization.XmlSerializer xmlSer = new System.Xml.Serialization.XmlSerializer(typeof(CICMMetadataType)); + xmlSer.Serialize(xmlFs, sidecar); + xmlFs.Close(); + } + + Statistics.AddMedia(dskType, true); + } + } +} diff --git a/DiscImageChef.Core/Devices/Dumping/SecureDigital.cs b/DiscImageChef.Core/Devices/Dumping/SecureDigital.cs new file mode 100644 index 000000000..d77e914c8 --- /dev/null +++ b/DiscImageChef.Core/Devices/Dumping/SecureDigital.cs @@ -0,0 +1,50 @@ +// /*************************************************************************** +// The Disc Image Chef +// ---------------------------------------------------------------------------- +// +// Filename : SecureDigital.cs +// Version : 1.0 +// Author(s) : Natalia Portillo +// +// Component : Component +// +// Revision : $Revision$ +// Last change by : $Author$ +// Date : $Date$ +// +// --[ Description ] ---------------------------------------------------------- +// +// Description +// +// --[ License ] -------------------------------------------------------------- +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . +// +// ---------------------------------------------------------------------------- +// Copyright (C) 2011-2015 Claunia.com +// ****************************************************************************/ +// //$Id$ +using System; +using DiscImageChef.Devices; + +namespace DiscImageChef.Core.Devices.Dumping +{ + public class SecureDigital + { + public static void Dump(Device dev, string devicePath, string outputPrefix, ushort retryPasses, bool force, bool dumpRaw, bool persistent, bool stopOnError) + { + throw new NotImplementedException("MMC/SD devices not yet supported."); + } + } +} diff --git a/DiscImageChef.Core/DiscImageChef.Core.csproj b/DiscImageChef.Core/DiscImageChef.Core.csproj index 11a44f3aa..73a1466cf 100644 --- a/DiscImageChef.Core/DiscImageChef.Core.csproj +++ b/DiscImageChef.Core/DiscImageChef.Core.csproj @@ -45,6 +45,11 @@ + + + + + @@ -91,11 +96,16 @@ {0BEB3088-B634-4289-AE17-CDF2D25D00D5} DiscImageChef.Decoders + + {9183F2E0-A879-4F23-9EE3-C6908F1332B2} + DiscImageChef.Interop + + diff --git a/DiscImageChef/ChangeLog b/DiscImageChef/ChangeLog index f100a0d77..1aee8c675 100644 --- a/DiscImageChef/ChangeLog +++ b/DiscImageChef/ChangeLog @@ -1,3 +1,11 @@ +2017-05-27 Natalia Portillo + + * Commands/DumpMedia.cs: + * Commands/MediaInfo.cs: + * Commands/DeviceInfo.cs: + Refactor: Move dumping code, and misc file writing code, to + Core. + 2017-05-27 Natalia Portillo * Commands/MediaScan.cs: diff --git a/DiscImageChef/Commands/DeviceInfo.cs b/DiscImageChef/Commands/DeviceInfo.cs index 1a8bec967..99e5ce401 100644 --- a/DiscImageChef/Commands/DeviceInfo.cs +++ b/DiscImageChef/Commands/DeviceInfo.cs @@ -36,6 +36,7 @@ using System.IO; using DiscImageChef.Console; using System.Text; using DiscImageChef.Decoders.ATA; +using DiscImageChef.Core; namespace DiscImageChef.Commands { @@ -187,7 +188,7 @@ namespace DiscImageChef.Commands break; } - doWriteFile(options.OutputPrefix, "_ata_identify.bin", "ATA IDENTIFY", ataBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, "_ata_identify.bin", "ATA IDENTIFY", ataBuf); DicConsole.WriteLine(Identify.Prettify(ataBuf)); @@ -250,7 +251,7 @@ namespace DiscImageChef.Commands break; } - doWriteFile(options.OutputPrefix, "_atapi_identify.bin", "ATAPI IDENTIFY", ataBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, "_atapi_identify.bin", "ATAPI IDENTIFY", ataBuf); DicConsole.WriteLine(Identify.Prettify(ataBuf)); @@ -274,7 +275,7 @@ namespace DiscImageChef.Commands if(dev.Type != DeviceType.ATAPI) DicConsole.WriteLine("SCSI device"); - doWriteFile(options.OutputPrefix, "_scsi_inquiry.bin", "SCSI INQUIRY", inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, "_scsi_inquiry.bin", "SCSI INQUIRY", inqBuf); Decoders.SCSI.Inquiry.SCSIInquiry? inq = Decoders.SCSI.Inquiry.Decode(inqBuf); DicConsole.WriteLine(Decoders.SCSI.Inquiry.Prettify(inq)); @@ -296,7 +297,7 @@ namespace DiscImageChef.Commands { DicConsole.WriteLine("ASCII Page {0:X2}h: {1}", page, Decoders.SCSI.EVPD.DecodeASCIIPage(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else if(page == 0x80) @@ -305,7 +306,7 @@ namespace DiscImageChef.Commands if(!sense) { DicConsole.WriteLine("Unit Serial Number: {0}", Decoders.SCSI.EVPD.DecodePage80(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else if(page == 0x81) @@ -314,7 +315,7 @@ namespace DiscImageChef.Commands if(!sense) { DicConsole.WriteLine("{0}", Decoders.SCSI.EVPD.PrettifyPage_81(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else if(page == 0x82) @@ -323,7 +324,7 @@ namespace DiscImageChef.Commands if(!sense) { DicConsole.WriteLine("ASCII implemented operating definitions: {0}", Decoders.SCSI.EVPD.DecodePage82(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else if(page == 0x83) @@ -332,7 +333,7 @@ namespace DiscImageChef.Commands if(!sense) { DicConsole.WriteLine("{0}", Decoders.SCSI.EVPD.PrettifyPage_83(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else if(page == 0x84) @@ -341,7 +342,7 @@ namespace DiscImageChef.Commands if(!sense) { DicConsole.WriteLine("{0}", Decoders.SCSI.EVPD.PrettifyPage_84(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else if(page == 0x85) @@ -350,7 +351,7 @@ namespace DiscImageChef.Commands if(!sense) { DicConsole.WriteLine("{0}", Decoders.SCSI.EVPD.PrettifyPage_85(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else if(page == 0x86) @@ -359,7 +360,7 @@ namespace DiscImageChef.Commands if(!sense) { DicConsole.WriteLine("{0}", Decoders.SCSI.EVPD.PrettifyPage_86(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else if(page == 0x89) @@ -368,7 +369,7 @@ namespace DiscImageChef.Commands if(!sense) { DicConsole.WriteLine("{0}", Decoders.SCSI.EVPD.PrettifyPage_89(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else if(page == 0xB0) @@ -377,7 +378,7 @@ namespace DiscImageChef.Commands if(!sense) { DicConsole.WriteLine("{0}", Decoders.SCSI.EVPD.PrettifyPage_B0(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else if(page == 0xB1) @@ -386,7 +387,7 @@ namespace DiscImageChef.Commands if(!sense) { DicConsole.WriteLine("Manufacturer-assigned Serial Number: {0}", Decoders.SCSI.EVPD.DecodePageB1(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else if(page == 0xB2) @@ -395,7 +396,7 @@ namespace DiscImageChef.Commands if(!sense) { DicConsole.WriteLine("TapeAlert Supported Flags Bitmap: 0x{0:X16}", Decoders.SCSI.EVPD.DecodePageB2(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else if(page == 0xB3) @@ -404,7 +405,7 @@ namespace DiscImageChef.Commands if(!sense) { DicConsole.WriteLine("Automation Device Serial Number: {0}", Decoders.SCSI.EVPD.DecodePageB3(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else if(page == 0xB4) @@ -413,7 +414,7 @@ namespace DiscImageChef.Commands if(!sense) { DicConsole.WriteLine("Data Transfer Device Element Address: 0x{0}", Decoders.SCSI.EVPD.DecodePageB4(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else if(page == 0xC0 && StringHandlers.CToString(inq.Value.VendorIdentification).ToLowerInvariant().Trim() == "quantum") @@ -422,7 +423,7 @@ namespace DiscImageChef.Commands if(!sense) { DicConsole.WriteLine("{0}", Decoders.SCSI.EVPD.PrettifyPage_C0_Quantum(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else if(page == 0xC0 && StringHandlers.CToString(inq.Value.VendorIdentification).ToLowerInvariant().Trim() == "seagate") @@ -431,7 +432,7 @@ namespace DiscImageChef.Commands if(!sense) { DicConsole.WriteLine("{0}", Decoders.SCSI.EVPD.PrettifyPage_C0_Seagate(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else if(page == 0xC0 && StringHandlers.CToString(inq.Value.VendorIdentification).ToLowerInvariant().Trim() == "ibm") @@ -440,7 +441,7 @@ namespace DiscImageChef.Commands if(!sense) { DicConsole.WriteLine("{0}", Decoders.SCSI.EVPD.PrettifyPage_C0_IBM(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else if(page == 0xC1 && StringHandlers.CToString(inq.Value.VendorIdentification).ToLowerInvariant().Trim() == "ibm") @@ -449,7 +450,7 @@ namespace DiscImageChef.Commands if(!sense) { DicConsole.WriteLine("{0}", Decoders.SCSI.EVPD.PrettifyPage_C1_IBM(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else if((page == 0xC0 || page == 0xC1) && StringHandlers.CToString(inq.Value.VendorIdentification).ToLowerInvariant().Trim() == "certance") @@ -458,7 +459,7 @@ namespace DiscImageChef.Commands if(!sense) { DicConsole.WriteLine("{0}", Decoders.SCSI.EVPD.PrettifyPage_C0_C1_Certance(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else if((page == 0xC2 || page == 0xC3 || page == 0xC4 || page == 0xC5 || page == 0xC6) && @@ -468,7 +469,7 @@ namespace DiscImageChef.Commands if(!sense) { DicConsole.WriteLine("{0}", Decoders.SCSI.EVPD.PrettifyPage_C2_C3_C4_C5_C6_Certance(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else if((page == 0xC0 || page == 0xC1 || page == 0xC2 || page == 0xC3 || page == 0xC4 || page == 0xC5) && @@ -478,7 +479,7 @@ namespace DiscImageChef.Commands if(!sense) { DicConsole.WriteLine("{0}", Decoders.SCSI.EVPD.PrettifyPage_C0_to_C5_HP(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else if(page == 0xDF && StringHandlers.CToString(inq.Value.VendorIdentification).ToLowerInvariant().Trim() == "certance") @@ -487,7 +488,7 @@ namespace DiscImageChef.Commands if(!sense) { DicConsole.WriteLine("{0}", Decoders.SCSI.EVPD.PrettifyPage_DF_Certance(inqBuf)); - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } else @@ -499,7 +500,7 @@ namespace DiscImageChef.Commands sense = dev.ScsiInquiry(out inqBuf, out senseBuf, page); if(!sense) { - doWriteFile(options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, string.Format("_scsi_evpd_{0:X2}h.bin", page), string.Format("SCSI INQUIRY EVPD {0:X2}h", page), inqBuf); } } } @@ -532,7 +533,7 @@ namespace DiscImageChef.Commands } if(!sense) - doWriteFile(options.OutputPrefix, "_scsi_modesense.bin", "SCSI MODE SENSE", modeBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, "_scsi_modesense.bin", "SCSI MODE SENSE", modeBuf); if(decMode.HasValue) { @@ -881,7 +882,7 @@ namespace DiscImageChef.Commands if(!sense) { - doWriteFile(options.OutputPrefix, "_mmc_getconfiguration.bin", "MMC GET CONFIGURATION", confBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, "_mmc_getconfiguration.bin", "MMC GET CONFIGURATION", confBuf); Decoders.SCSI.MMC.Features.SeparatedFeatures ftr = Decoders.SCSI.MMC.Features.Separate(confBuf); @@ -1170,7 +1171,7 @@ namespace DiscImageChef.Commands if(!plxtSense) { - doWriteFile(options.OutputPrefix, "_plextor_eeprom.bin", "PLEXTOR READ EEPROM", plxtBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, "_plextor_eeprom.bin", "PLEXTOR READ EEPROM", plxtBuf); ushort discs; uint cdReadTime, cdWriteTime, dvdReadTime = 0, dvdWriteTime = 0; @@ -1366,7 +1367,7 @@ namespace DiscImageChef.Commands DicConsole.ErrorWriteLine("READ BLOCK LIMITS:\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(options.OutputPrefix, "_ssc_readblocklimits.bin", "SSC READ BLOCK LIMITS", seqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, "_ssc_readblocklimits.bin", "SSC READ BLOCK LIMITS", seqBuf); DicConsole.WriteLine("Block limits for device:"); DicConsole.WriteLine(Decoders.SCSI.SSC.BlockLimits.Prettify(seqBuf)); } @@ -1376,7 +1377,7 @@ namespace DiscImageChef.Commands DicConsole.ErrorWriteLine("REPORT DENSITY SUPPORT:\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(options.OutputPrefix, "_ssc_reportdensitysupport.bin", "SSC REPORT DENSITY SUPPORT", seqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, "_ssc_reportdensitysupport.bin", "SSC REPORT DENSITY SUPPORT", seqBuf); Decoders.SCSI.SSC.DensitySupport.DensitySupportHeader? dens = Decoders.SCSI.SSC.DensitySupport.DecodeDensity(seqBuf); if(dens.HasValue) { @@ -1390,7 +1391,7 @@ namespace DiscImageChef.Commands DicConsole.ErrorWriteLine("REPORT DENSITY SUPPORT (MEDIUM):\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(options.OutputPrefix, "_ssc_reportdensitysupport_medium.bin", "SSC REPORT DENSITY SUPPORT (MEDIUM)", seqBuf); + DataFile.WriteTo("Device-Info command", options.OutputPrefix, "_ssc_reportdensitysupport_medium.bin", "SSC REPORT DENSITY SUPPORT (MEDIUM)", seqBuf); Decoders.SCSI.SSC.DensitySupport.MediaTypeSupportHeader? meds = Decoders.SCSI.SSC.DensitySupport.DecodeMediumType(seqBuf); if(meds.HasValue) { @@ -1410,29 +1411,6 @@ namespace DiscImageChef.Commands Core.Statistics.AddCommand("device-info"); } - - static void doWriteFile(string outputPrefix, string outputSuffix, string whatWriting, byte[] data) - { - if(!string.IsNullOrEmpty(outputPrefix)) - { - if(!File.Exists(outputPrefix + outputSuffix)) - { - try - { - DicConsole.DebugWriteLine("Device-Info command", "Writing " + whatWriting + " to {0}{1}", outputPrefix, outputSuffix); - FileStream outputFs = new FileStream(outputPrefix + outputSuffix, FileMode.CreateNew); - outputFs.Write(data, 0, data.Length); - outputFs.Close(); - } - catch - { - DicConsole.ErrorWriteLine("Unable to write file {0}{1}", outputPrefix, outputSuffix); - } - } - else - DicConsole.ErrorWriteLine("Not overwriting file {0}{1}", outputPrefix, outputSuffix); - } - } } } diff --git a/DiscImageChef/Commands/DumpMedia.cs b/DiscImageChef/Commands/DumpMedia.cs index f09ca8e8f..c246343d8 100644 --- a/DiscImageChef/Commands/DumpMedia.cs +++ b/DiscImageChef/Commands/DumpMedia.cs @@ -36,6 +36,7 @@ using System.IO; using DiscImageChef.CommonTypes; using DiscImageChef.Console; using DiscImageChef.Core; +using DiscImageChef.Core.Devices.Dumping; using DiscImageChef.Core.Logging; using DiscImageChef.Decoders.PCMCIA; using DiscImageChef.Devices; @@ -49,10 +50,6 @@ namespace DiscImageChef.Commands { public static class DumpMedia { - static bool aborted; - static FileStream dataFs; - static MHDDLog mhddLog; - static IBGLog ibgLog; // TODO: Implement dump map public static void doDumpMedia(DumpMediaOptions options) @@ -79,9 +76,6 @@ namespace DiscImageChef.Commands options.DevicePath = "\\\\.\\" + char.ToUpper(options.DevicePath[0]) + ':'; } - mhddLog = null; - ibgLog = null; - Device dev = new Device(options.DevicePath); if(dev.Error) @@ -95,18 +89,18 @@ namespace DiscImageChef.Commands switch(dev.Type) { case DeviceType.ATA: - doATAMediaScan(options, dev); + ATA.Dump(dev, options.DevicePath, options.OutputPrefix, options.RetryPasses, options.Force, options.Raw, options.Persistent, options.StopOnError); break; case DeviceType.MMC: case DeviceType.SecureDigital: - doSDMediaScan(options, dev); + SecureDigital.Dump(dev, options.DevicePath, options.OutputPrefix, options.RetryPasses, options.Force, options.Raw, options.Persistent, options.StopOnError); break; case DeviceType.NVMe: - doNVMeMediaScan(options, dev); + NVMe.Dump(dev, options.DevicePath, options.OutputPrefix, options.RetryPasses, options.Force, options.Raw, options.Persistent, options.StopOnError); break; case DeviceType.ATAPI: case DeviceType.SCSI: - doSCSIMediaScan(options, dev); + SCSI.Dump(dev, options.DevicePath, options.OutputPrefix, options.RetryPasses, options.Force, options.Raw, options.Persistent, options.StopOnError); break; default: throw new NotSupportedException("Unknown device type."); @@ -114,4455 +108,5 @@ namespace DiscImageChef.Commands Core.Statistics.AddCommand("dump-media"); } - - static void doATAMediaScan(DumpMediaOptions options, Device dev) - { - if(options.Raw) - { - DicConsole.ErrorWriteLine("Raw dumping not yet supported in ATA devices."); - - if(options.Force) - DicConsole.ErrorWriteLine("Continuing..."); - else - { - DicConsole.ErrorWriteLine("Aborting..."); - return; - } - } - - byte[] cmdBuf; - bool sense; - ulong blocks = 0; - uint blockSize = 512; - ushort currentProfile = 0x0001; - Decoders.ATA.AtaErrorRegistersCHS errorChs; - Decoders.ATA.AtaErrorRegistersLBA28 errorLba; - Decoders.ATA.AtaErrorRegistersLBA48 errorLba48; - bool lbaMode = false; - byte heads = 0, sectors = 0; - ushort cylinders = 0; - uint timeout = 5; - double duration; - - sense = dev.AtaIdentify(out cmdBuf, out errorChs); - if(!sense && Decoders.ATA.Identify.Decode(cmdBuf).HasValue) - { - Decoders.ATA.Identify.IdentifyDevice ataId = Decoders.ATA.Identify.Decode(cmdBuf).Value; - - CICMMetadataType sidecar = new CICMMetadataType(); - sidecar.BlockMedia = new BlockMediaType[1]; - sidecar.BlockMedia[0] = new BlockMediaType(); - - if(dev.IsUSB) - { - sidecar.BlockMedia[0].USB = new USBType(); - sidecar.BlockMedia[0].USB.ProductID = dev.USBProductID; - sidecar.BlockMedia[0].USB.VendorID = dev.USBVendorID; - sidecar.BlockMedia[0].USB.Descriptors = new DumpType(); - sidecar.BlockMedia[0].USB.Descriptors.Image = options.OutputPrefix + ".usbdescriptors.bin"; - sidecar.BlockMedia[0].USB.Descriptors.Size = dev.USBDescriptors.Length; - sidecar.BlockMedia[0].USB.Descriptors.Checksums = Core.Checksum.GetChecksums(dev.USBDescriptors).ToArray(); - writeToFile(sidecar.BlockMedia[0].USB.Descriptors.Image, dev.USBDescriptors); - } - - if(dev.IsPCMCIA) - { - sidecar.BlockMedia[0].PCMCIA = new PCMCIAType(); - sidecar.BlockMedia[0].PCMCIA.CIS = new DumpType(); - sidecar.BlockMedia[0].PCMCIA.CIS.Image = options.OutputPrefix + ".cis.bin"; - sidecar.BlockMedia[0].PCMCIA.CIS.Size = dev.CIS.Length; - sidecar.BlockMedia[0].PCMCIA.CIS.Checksums = Core.Checksum.GetChecksums(dev.CIS).ToArray(); - writeToFile(sidecar.BlockMedia[0].PCMCIA.CIS.Image, dev.CIS); - Decoders.PCMCIA.Tuple[] tuples = CIS.GetTuples(dev.CIS); - if(tuples != null) - { - foreach(Decoders.PCMCIA.Tuple tuple in tuples) - { - if(tuple.Code == TupleCodes.CISTPL_MANFID) - { - ManufacturerIdentificationTuple manfid = CIS.DecodeManufacturerIdentificationTuple(tuple); - - if(manfid != null) - { - sidecar.BlockMedia[0].PCMCIA.ManufacturerCode = manfid.ManufacturerID; - sidecar.BlockMedia[0].PCMCIA.CardCode = manfid.CardID; - sidecar.BlockMedia[0].PCMCIA.ManufacturerCodeSpecified = true; - sidecar.BlockMedia[0].PCMCIA.CardCodeSpecified = true; - } - } - else if(tuple.Code == TupleCodes.CISTPL_VERS_1) - { - Level1VersionTuple vers = CIS.DecodeLevel1VersionTuple(tuple); - - if(vers != null) - { - sidecar.BlockMedia[0].PCMCIA.Manufacturer = vers.Manufacturer; - sidecar.BlockMedia[0].PCMCIA.ProductName = vers.Product; - sidecar.BlockMedia[0].PCMCIA.Compliance = string.Format("{0}.{1}", vers.MajorVersion, vers.MinorVersion); - sidecar.BlockMedia[0].PCMCIA.AdditionalInformation = vers.AdditionalInformation; - } - } - } - } - } - - sidecar.BlockMedia[0].ATA = new ATAType(); - sidecar.BlockMedia[0].ATA.Identify = new DumpType(); - sidecar.BlockMedia[0].ATA.Identify.Image = options.OutputPrefix + ".identify.bin"; - sidecar.BlockMedia[0].ATA.Identify.Size = cmdBuf.Length; - sidecar.BlockMedia[0].ATA.Identify.Checksums = Core.Checksum.GetChecksums(cmdBuf).ToArray(); - writeToFile(sidecar.BlockMedia[0].ATA.Identify.Image, cmdBuf); - - if(ataId.CurrentCylinders > 0 && ataId.CurrentHeads > 0 && ataId.CurrentSectorsPerTrack > 0) - { - cylinders = ataId.CurrentCylinders; - heads = (byte)ataId.CurrentHeads; - sectors = (byte)ataId.CurrentSectorsPerTrack; - blocks = (ulong)(cylinders * heads * sectors); - } - - if((ataId.CurrentCylinders == 0 || ataId.CurrentHeads == 0 || ataId.CurrentSectorsPerTrack == 0) && - (ataId.Cylinders > 0 && ataId.Heads > 0 && ataId.SectorsPerTrack > 0)) - { - cylinders = ataId.Cylinders; - heads = (byte)ataId.Heads; - sectors = (byte)ataId.SectorsPerTrack; - blocks = (ulong)(cylinders * heads * sectors); - } - - if(ataId.Capabilities.HasFlag(Decoders.ATA.Identify.CapabilitiesBit.LBASupport)) - { - blocks = ataId.LBASectors; - lbaMode = true; - } - - if(ataId.CommandSet2.HasFlag(Decoders.ATA.Identify.CommandSetBit2.LBA48)) - { - blocks = ataId.LBA48Sectors; - lbaMode = true; - } - - uint physicalsectorsize = blockSize; - if((ataId.PhysLogSectorSize & 0x8000) == 0x0000 && - (ataId.PhysLogSectorSize & 0x4000) == 0x4000) - { - if((ataId.PhysLogSectorSize & 0x1000) == 0x1000) - { - if(ataId.LogicalSectorWords <= 255 || ataId.LogicalAlignment == 0xFFFF) - blockSize = 512; - else - blockSize = ataId.LogicalSectorWords * 2; - } - else - blockSize = 512; - - if((ataId.PhysLogSectorSize & 0x2000) == 0x2000) - { -#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created - physicalsectorsize = blockSize * (uint)Math.Pow(2, (double)(ataId.PhysLogSectorSize & 0xF)); -#pragma warning restore IDE0004 // Cast is necessary, otherwise incorrect value is created - } - else - physicalsectorsize = blockSize; - } - else - { - blockSize = 512; - physicalsectorsize = 512; - } - - bool ReadLba = false; - bool ReadRetryLba = false; - bool ReadDmaLba = false; - bool ReadDmaRetryLba = false; - - bool ReadLba48 = false; - bool ReadDmaLba48 = false; - - bool Read = false; - bool ReadRetry = false; - bool ReadDma = false; - bool ReadDmaRetry = false; - - sense = dev.Read(out cmdBuf, out errorChs, false, 0, 0, 1, 1, timeout, out duration); - Read = (!sense && (errorChs.status & 0x27) == 0 && errorChs.error == 0 && cmdBuf.Length > 0); - sense = dev.Read(out cmdBuf, out errorChs, true, 0, 0, 1, 1, timeout, out duration); - ReadRetry = (!sense && (errorChs.status & 0x27) == 0 && errorChs.error == 0 && cmdBuf.Length > 0); - sense = dev.ReadDma(out cmdBuf, out errorChs, false, 0, 0, 1, 1, timeout, out duration); - ReadDma = (!sense && (errorChs.status & 0x27) == 0 && errorChs.error == 0 && cmdBuf.Length > 0); - sense = dev.ReadDma(out cmdBuf, out errorChs, true, 0, 0, 1, 1, timeout, out duration); - ReadDmaRetry = (!sense && (errorChs.status & 0x27) == 0 && errorChs.error == 0 && cmdBuf.Length > 0); - - sense = dev.Read(out cmdBuf, out errorLba, false, 0, 1, timeout, out duration); - ReadLba = (!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); - sense = dev.Read(out cmdBuf, out errorLba, true, 0, 1, timeout, out duration); - ReadRetryLba = (!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); - sense = dev.ReadDma(out cmdBuf, out errorLba, false, 0, 1, timeout, out duration); - ReadDmaLba = (!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); - sense = dev.ReadDma(out cmdBuf, out errorLba, true, 0, 1, timeout, out duration); - ReadDmaRetryLba = (!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); - - sense = dev.Read(out cmdBuf, out errorLba48, 0, 1, timeout, out duration); - ReadLba48 = (!sense && (errorLba48.status & 0x27) == 0 && errorLba48.error == 0 && cmdBuf.Length > 0); - sense = dev.ReadDma(out cmdBuf, out errorLba48, 0, 1, timeout, out duration); - ReadDmaLba48 = (!sense && (errorLba48.status & 0x27) == 0 && errorLba48.error == 0 && cmdBuf.Length > 0); - - if(!lbaMode) - { - if(blocks > 0xFFFFFFF && !ReadLba48 && !ReadDmaLba48) - { - DicConsole.ErrorWriteLine("Device needs 48-bit LBA commands but I can't issue them... Aborting."); - return; - } - - if(!ReadLba && !ReadRetryLba && !ReadDmaLba && !ReadDmaRetryLba) - { - DicConsole.ErrorWriteLine("Device needs 28-bit LBA commands but I can't issue them... Aborting."); - return; - } - } - else - { - if(!Read && !ReadRetry && !ReadDma && !ReadDmaRetry) - { - DicConsole.ErrorWriteLine("Device needs CHS commands but I can't issue them... Aborting."); - return; - } - } - - if(ReadDmaLba48) - DicConsole.WriteLine("Using ATA READ DMA EXT command."); - else if(ReadLba48) - DicConsole.WriteLine("Using ATA READ EXT command."); - else if(ReadDmaRetryLba) - DicConsole.WriteLine("Using ATA READ DMA command with retries (LBA)."); - else if(ReadDmaLba) - DicConsole.WriteLine("Using ATA READ DMA command (LBA)."); - else if(ReadRetryLba) - DicConsole.WriteLine("Using ATA READ command with retries (LBA)."); - else if(ReadLba) - DicConsole.WriteLine("Using ATA READ command (LBA)."); - else if(ReadDmaRetry) - DicConsole.WriteLine("Using ATA READ DMA command with retries (CHS)."); - else if(ReadDma) - DicConsole.WriteLine("Using ATA READ DMA command (CHS)."); - else if(ReadRetry) - DicConsole.WriteLine("Using ATA READ command with retries (CHS)."); - else if(Read) - DicConsole.WriteLine("Using ATA READ command (CHS)."); - - uint blocksToRead = 64; - bool error = true; - while(lbaMode) - { - if(ReadDmaLba48) - { - sense = dev.ReadDma(out cmdBuf, out errorLba48, 0, (byte)blocksToRead, timeout, out duration); - error = !(!sense && (errorLba48.status & 0x27) == 0 && errorLba48.error == 0 && cmdBuf.Length > 0); - } - else if(ReadLba48) - { - sense = dev.Read(out cmdBuf, out errorLba48, 0, (byte)blocksToRead, timeout, out duration); - error = !(!sense && (errorLba48.status & 0x27) == 0 && errorLba48.error == 0 && cmdBuf.Length > 0); - } - else if(ReadDmaRetryLba) - { - sense = dev.ReadDma(out cmdBuf, out errorLba, true, 0, (byte)blocksToRead, timeout, out duration); - error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); - } - else if(ReadDmaLba) - { - sense = dev.ReadDma(out cmdBuf, out errorLba, false, 0, (byte)blocksToRead, timeout, out duration); - error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); - } - else if(ReadRetryLba) - { - sense = dev.Read(out cmdBuf, out errorLba, true, 0, (byte)blocksToRead, timeout, out duration); - error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); - } - else if(ReadLba) - { - sense = dev.Read(out cmdBuf, out errorLba, false, 0, (byte)blocksToRead, timeout, out duration); - error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); - } - - if(error) - blocksToRead /= 2; - - if(!error || blocksToRead == 1) - break; - } - - if(error && lbaMode) - { - DicConsole.ErrorWriteLine("Device error {0} trying to guess ideal transfer length.", dev.LastError); - return; - } - - ulong A = 0; // <3ms - ulong B = 0; // >=3ms, <10ms - ulong C = 0; // >=10ms, <50ms - ulong D = 0; // >=50ms, <150ms - ulong E = 0; // >=150ms, <500ms - ulong F = 0; // >=500ms - ulong errored = 0; - DateTime start; - DateTime end; - double totalDuration = 0; - double totalChkDuration = 0; - double currentSpeed = 0; - double maxSpeed = double.MinValue; - double minSpeed = double.MaxValue; - List unreadableSectors = new List(); - Core.Checksum dataChk; - - aborted = false; - System.Console.CancelKeyPress += (sender, e) => - { - e.Cancel = aborted = true; - }; - - if(lbaMode) - { - DicConsole.WriteLine("Reading {0} sectors at a time.", blocksToRead); - - mhddLog = new MHDDLog(options.OutputPrefix + ".mhddlog.bin", dev, blocks, blockSize, blocksToRead); - ibgLog = new IBGLog(options.OutputPrefix + ".ibg", currentProfile); - initDataFile(options.OutputPrefix + ".bin"); - - start = DateTime.UtcNow; - for(ulong i = 0; i < blocks; i += blocksToRead) - { - if(aborted) - break; - - double cmdDuration = 0; - - if((blocks - i) < blocksToRead) - blocksToRead = (byte)(blocks - i); - -#pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator - if(currentSpeed > maxSpeed && currentSpeed != 0) - maxSpeed = currentSpeed; - if(currentSpeed < minSpeed && currentSpeed != 0) - minSpeed = currentSpeed; -#pragma warning restore RECS0018 // Comparison of floating point numbers with equality operator - - DicConsole.Write("\rReading sector {0} of {1} ({2:F3} MiB/sec.)", i, blocks, currentSpeed); - - error = true; - byte status = 0, errorByte = 0; - - if(ReadDmaLba48) - { - sense = dev.ReadDma(out cmdBuf, out errorLba48, i, (byte)blocksToRead, timeout, out cmdDuration); - error = !(!sense && (errorLba48.status & 0x27) == 0 && errorLba48.error == 0 && cmdBuf.Length > 0); - status = errorLba48.status; - errorByte = errorLba48.error; - } - else if(ReadLba48) - { - sense = dev.Read(out cmdBuf, out errorLba48, i, (byte)blocksToRead, timeout, out cmdDuration); - error = !(!sense && (errorLba48.status & 0x27) == 0 && errorLba48.error == 0 && cmdBuf.Length > 0); - status = errorLba48.status; - errorByte = errorLba48.error; - } - else if(ReadDmaRetryLba) - { - sense = dev.ReadDma(out cmdBuf, out errorLba, true, (uint)i, (byte)blocksToRead, timeout, out cmdDuration); - error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); - status = errorLba.status; - errorByte = errorLba.error; - } - else if(ReadDmaLba) - { - sense = dev.ReadDma(out cmdBuf, out errorLba, false, (uint)i, (byte)blocksToRead, timeout, out cmdDuration); - error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); - status = errorLba.status; - errorByte = errorLba.error; - } - else if(ReadRetryLba) - { - sense = dev.Read(out cmdBuf, out errorLba, true, (uint)i, (byte)blocksToRead, timeout, out cmdDuration); - error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); - status = errorLba.status; - errorByte = errorLba.error; - } - else if(ReadLba) - { - sense = dev.Read(out cmdBuf, out errorLba, false, (uint)i, (byte)blocksToRead, timeout, out cmdDuration); - error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); - status = errorLba.status; - errorByte = errorLba.error; - } - - if(!error) - { - if(cmdDuration >= 500) - { - F += blocksToRead; - } - else if(cmdDuration >= 150) - { - E += blocksToRead; - } - else if(cmdDuration >= 50) - { - D += blocksToRead; - } - else if(cmdDuration >= 10) - { - C += blocksToRead; - } - else if(cmdDuration >= 3) - { - B += blocksToRead; - } - else - { - A += blocksToRead; - } - - mhddLog.Write(i, cmdDuration); - ibgLog.Write(i, currentSpeed * 1024); - writeToDataFile(cmdBuf); - } - else - { - DicConsole.DebugWriteLine("Media-Scan", "ATA ERROR: {0} STATUS: {1}", errorByte, status); - errored += blocksToRead; - unreadableSectors.Add(i); - if(cmdDuration < 500) - mhddLog.Write(i, 65535); - else - mhddLog.Write(i, cmdDuration); - - ibgLog.Write(i, 0); - writeToDataFile(new byte[blockSize * blocksToRead]); - } - -#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created - currentSpeed = ((double)blockSize * blocksToRead / (double)1048576) / (cmdDuration / (double)1000); -#pragma warning restore IDE0004 // Cast is necessary, otherwise incorrect value is created - GC.Collect(); - } - end = DateTime.Now; - DicConsole.WriteLine(); - mhddLog.Close(); -#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created - ibgLog.Close(dev, blocks, blockSize, (end - start).TotalSeconds, currentSpeed * 1024, (((double)blockSize * (double)(blocks + 1)) / 1024) / (totalDuration / 1000), options.DevicePath); -#pragma warning restore IDE0004 // Cast is necessary, otherwise incorrect value is created - - #region Error handling - if(unreadableSectors.Count > 0 && !aborted) - { - List tmpList = new List(); - - foreach(ulong ur in unreadableSectors) - { - for(ulong i = ur; i < ur + blocksToRead; i++) - tmpList.Add(i); - } - - tmpList.Sort(); - - int pass = 0; - bool forward = true; - bool runningPersistent = false; - - unreadableSectors = tmpList; - - repeatRetryLba: - ulong[] tmpArray = unreadableSectors.ToArray(); - foreach(ulong badSector in tmpArray) - { - if(aborted) - break; - - double cmdDuration = 0; - - DicConsole.Write("\rRetrying sector {0}, pass {1}, {3}{2}", badSector, pass + 1, forward ? "forward" : "reverse", runningPersistent ? "recovering partial data, " : ""); - - if(ReadDmaLba48) - { - sense = dev.ReadDma(out cmdBuf, out errorLba48, badSector, 1, timeout, out cmdDuration); - error = !(!sense && (errorLba48.status & 0x27) == 0 && errorLba48.error == 0 && cmdBuf.Length > 0); - } - else if(ReadLba48) - { - sense = dev.Read(out cmdBuf, out errorLba48, badSector, 1, timeout, out cmdDuration); - error = !(!sense && (errorLba48.status & 0x27) == 0 && errorLba48.error == 0 && cmdBuf.Length > 0); - } - else if(ReadDmaRetryLba) - { - sense = dev.ReadDma(out cmdBuf, out errorLba, true, (uint)badSector, 1, timeout, out cmdDuration); - error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); - } - else if(ReadDmaLba) - { - sense = dev.ReadDma(out cmdBuf, out errorLba, false, (uint)badSector, 1, timeout, out cmdDuration); - error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); - } - else if(ReadRetryLba) - { - sense = dev.Read(out cmdBuf, out errorLba, true, (uint)badSector, 1, timeout, out cmdDuration); - error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); - } - else if(ReadLba) - { - sense = dev.Read(out cmdBuf, out errorLba, false, (uint)badSector, 1, timeout, out cmdDuration); - error = !(!sense && (errorLba.status & 0x27) == 0 && errorLba.error == 0 && cmdBuf.Length > 0); - } - - totalDuration += cmdDuration; - - if(!error) - { - unreadableSectors.Remove(badSector); - writeToDataFileAtPosition(cmdBuf, badSector, blockSize); - } - else if(runningPersistent) - writeToDataFileAtPosition(cmdBuf, badSector, blockSize); - } - - if(pass < options.RetryPasses && !aborted && unreadableSectors.Count > 0) - { - pass++; - forward = !forward; - unreadableSectors.Sort(); - unreadableSectors.Reverse(); - goto repeatRetryLba; - } - - DicConsole.WriteLine(); - } - #endregion Error handling LBA - } - else - { - mhddLog = new MHDDLog(options.OutputPrefix + ".mhddlog.bin", dev, blocks, blockSize, blocksToRead); - ibgLog = new IBGLog(options.OutputPrefix + ".ibg", currentProfile); - initDataFile(options.OutputPrefix + ".bin"); - - ulong currentBlock = 0; - blocks = (ulong)(cylinders * heads * sectors); - start = DateTime.UtcNow; - for(ushort Cy = 0; Cy < cylinders; Cy++) - { - for(byte Hd = 0; Hd < heads; Hd++) - { - for(byte Sc = 1; Sc < sectors; Sc++) - { - if(aborted) - break; - - double cmdDuration = 0; - -#pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator - if(currentSpeed > maxSpeed && currentSpeed != 0) - maxSpeed = currentSpeed; - if(currentSpeed < minSpeed && currentSpeed != 0) - minSpeed = currentSpeed; -#pragma warning restore RECS0018 // Comparison of floating point numbers with equality operator - - DicConsole.Write("\rReading cylinder {0} head {1} sector {2} ({3:F3} MiB/sec.)", Cy, Hd, Sc, currentSpeed); - - error = true; - byte status = 0, errorByte = 0; - - if(ReadDmaRetry) - { - sense = dev.ReadDma(out cmdBuf, out errorChs, true, Cy, Hd, Sc, 1, timeout, out cmdDuration); - error = !(!sense && (errorChs.status & 0x27) == 0 && errorChs.error == 0 && cmdBuf.Length > 0); - status = errorChs.status; - errorByte = errorChs.error; - } - else if(ReadDma) - { - sense = dev.ReadDma(out cmdBuf, out errorChs, false, Cy, Hd, Sc, 1, timeout, out cmdDuration); - error = !(!sense && (errorChs.status & 0x27) == 0 && errorChs.error == 0 && cmdBuf.Length > 0); - status = errorChs.status; - errorByte = errorChs.error; - } - else if(ReadRetry) - { - sense = dev.Read(out cmdBuf, out errorChs, true, Cy, Hd, Sc, 1, timeout, out cmdDuration); - error = !(!sense && (errorChs.status & 0x27) == 0 && errorChs.error == 0 && cmdBuf.Length > 0); - status = errorChs.status; - errorByte = errorChs.error; - } - else if(Read) - { - sense = dev.Read(out cmdBuf, out errorChs, false, Cy, Hd, Sc, 1, timeout, out cmdDuration); - error = !(!sense && (errorChs.status & 0x27) == 0 && errorChs.error == 0 && cmdBuf.Length > 0); - status = errorChs.status; - errorByte = errorChs.error; - } - - totalDuration += cmdDuration; - - if(!error) - { - if(cmdDuration >= 500) - { - F += blocksToRead; - } - else if(cmdDuration >= 150) - { - E += blocksToRead; - } - else if(cmdDuration >= 50) - { - D += blocksToRead; - } - else if(cmdDuration >= 10) - { - C += blocksToRead; - } - else if(cmdDuration >= 3) - { - B += blocksToRead; - } - else - { - A += blocksToRead; - } - - mhddLog.Write(currentBlock, cmdDuration); - ibgLog.Write(currentBlock, currentSpeed * 1024); - writeToDataFile(cmdBuf); - } - else - { - DicConsole.DebugWriteLine("Media-Scan", "ATA ERROR: {0} STATUS: {1}", errorByte, status); - errored += blocksToRead; - unreadableSectors.Add(currentBlock); - if(cmdDuration < 500) - mhddLog.Write(currentBlock, 65535); - else - mhddLog.Write(currentBlock, cmdDuration); - - ibgLog.Write(currentBlock, 0); - writeToDataFile(new byte[blockSize]); - } - -#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created - currentSpeed = ((double)blockSize / (double)1048576) / (cmdDuration / (double)1000); -#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created - GC.Collect(); - - currentBlock++; - } - } - } - end = DateTime.Now; - DicConsole.WriteLine(); - mhddLog.Close(); -#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created - ibgLog.Close(dev, blocks, blockSize, (end - start).TotalSeconds, currentSpeed * 1024, (((double)blockSize * (double)(blocks + 1)) / 1024) / (totalDuration / 1000), options.DevicePath); -#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created - } - dataChk = new Core.Checksum(); - dataFs.Seek(0, SeekOrigin.Begin); - blocksToRead = 500; - - for(ulong i = 0; i < blocks; i += blocksToRead) - { - if(aborted) - break; - - if((blocks - i) < blocksToRead) - blocksToRead = (byte)(blocks - i); - - DicConsole.Write("\rChecksumming sector {0} of {1} ({2:F3} MiB/sec.)", i, blocks, currentSpeed); - - DateTime chkStart = DateTime.UtcNow; - byte[] dataToCheck = new byte[blockSize * blocksToRead]; - dataFs.Read(dataToCheck, 0, (int)(blockSize * blocksToRead)); - dataChk.Update(dataToCheck); - DateTime chkEnd = DateTime.UtcNow; - - double chkDuration = (chkEnd - chkStart).TotalMilliseconds; - totalChkDuration += chkDuration; - - currentSpeed = ((double)blockSize * blocksToRead / (double)1048576) / (chkDuration / (double)1000); - } - DicConsole.WriteLine(); - closeDataFile(); - end = DateTime.UtcNow; - - PluginBase plugins = new PluginBase(); - plugins.RegisterAllPlugins(); - ImagePlugin _imageFormat; - - FiltersList filtersList = new FiltersList(); - Filter inputFilter = filtersList.GetFilter(options.OutputPrefix + ".bin"); - - if(inputFilter == null) - { - DicConsole.ErrorWriteLine("Cannot open file just created, this should not happen."); - return; - } - - _imageFormat = ImageFormat.Detect(inputFilter); - PartitionType[] xmlFileSysInfo = null; - - try - { - if(!_imageFormat.OpenImage(inputFilter)) - _imageFormat = null; - } - catch - { - _imageFormat = null; - } - - if(_imageFormat != null) - { - List partitions = new List(); - - foreach(PartPlugin _partplugin in plugins.PartPluginsList.Values) - { - List _partitions; - - if(_partplugin.GetInformation(_imageFormat, out _partitions)) - { - partitions.AddRange(_partitions); - Core.Statistics.AddPartition(_partplugin.Name); - } - } - - if(partitions.Count > 0) - { - xmlFileSysInfo = new PartitionType[partitions.Count]; - for(int i = 0; i < partitions.Count; i++) - { - xmlFileSysInfo[i] = new PartitionType(); - xmlFileSysInfo[i].Description = partitions[i].PartitionDescription; - xmlFileSysInfo[i].EndSector = (int)(partitions[i].PartitionStartSector + partitions[i].PartitionSectors - 1); - xmlFileSysInfo[i].Name = partitions[i].PartitionName; - xmlFileSysInfo[i].Sequence = (int)partitions[i].PartitionSequence; - xmlFileSysInfo[i].StartSector = (int)partitions[i].PartitionStartSector; - xmlFileSysInfo[i].Type = partitions[i].PartitionType; - - List lstFs = new List(); - - foreach(Filesystem _plugin in plugins.PluginsList.Values) - { - try - { - if(_plugin.Identify(_imageFormat, partitions[i].PartitionStartSector, partitions[i].PartitionStartSector + partitions[i].PartitionSectors - 1)) - { - string foo; - _plugin.GetInformation(_imageFormat, partitions[i].PartitionStartSector, partitions[i].PartitionStartSector + partitions[i].PartitionSectors - 1, out foo); - lstFs.Add(_plugin.XmlFSType); - Core.Statistics.AddFilesystem(_plugin.XmlFSType.Type); - } - } -#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body - catch -#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body - { - //DicConsole.DebugWriteLine("Dump-media command", "Plugin {0} crashed", _plugin.Name); - } - } - - if(lstFs.Count > 0) - xmlFileSysInfo[i].FileSystems = lstFs.ToArray(); - } - } - else - { - xmlFileSysInfo = new PartitionType[1]; - xmlFileSysInfo[0] = new PartitionType(); - xmlFileSysInfo[0].EndSector = (int)(blocks - 1); - xmlFileSysInfo[0].StartSector = 0; - - List lstFs = new List(); - - foreach(Filesystem _plugin in plugins.PluginsList.Values) - { - try - { - if(_plugin.Identify(_imageFormat, (blocks - 1), 0)) - { - string foo; - _plugin.GetInformation(_imageFormat, (blocks - 1), 0, out foo); - lstFs.Add(_plugin.XmlFSType); - Core.Statistics.AddFilesystem(_plugin.XmlFSType.Type); - } - } -#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body - catch -#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body - { - //DicConsole.DebugWriteLine("Create-sidecar command", "Plugin {0} crashed", _plugin.Name); - } - } - - if(lstFs.Count > 0) - xmlFileSysInfo[0].FileSystems = lstFs.ToArray(); - } - } - - sidecar.BlockMedia[0].Checksums = dataChk.End().ToArray(); - string xmlDskTyp, xmlDskSubTyp; - if(dev.IsCompactFlash) - Metadata.MediaType.MediaTypeToString(MediaType.CompactFlash, out xmlDskTyp, out xmlDskSubTyp); - else if(dev.IsPCMCIA) - Metadata.MediaType.MediaTypeToString(MediaType.PCCardTypeI, out xmlDskTyp, out xmlDskSubTyp); - else - Metadata.MediaType.MediaTypeToString(MediaType.GENERIC_HDD, out xmlDskTyp, out xmlDskSubTyp); - sidecar.BlockMedia[0].DiskType = xmlDskTyp; - sidecar.BlockMedia[0].DiskSubType = xmlDskSubTyp; - // TODO: Implement device firmware revision - sidecar.BlockMedia[0].Image = new ImageType(); - sidecar.BlockMedia[0].Image.format = "Raw disk image (sector by sector copy)"; - sidecar.BlockMedia[0].Image.Value = options.OutputPrefix + ".bin"; - sidecar.BlockMedia[0].Interface = "ATA"; - sidecar.BlockMedia[0].LogicalBlocks = (long)blocks; - sidecar.BlockMedia[0].PhysicalBlockSize = (int)physicalsectorsize; - sidecar.BlockMedia[0].LogicalBlockSize = (int)blockSize; - sidecar.BlockMedia[0].Manufacturer = dev.Manufacturer; - sidecar.BlockMedia[0].Model = dev.Model; - sidecar.BlockMedia[0].Serial = dev.Serial; - sidecar.BlockMedia[0].Size = (long)(blocks * blockSize); - if(xmlFileSysInfo != null) - sidecar.BlockMedia[0].FileSystemInformation = xmlFileSysInfo; - if(cylinders > 0 && heads > 0 && sectors > 0) - { - sidecar.BlockMedia[0].Cylinders = cylinders; - sidecar.BlockMedia[0].CylindersSpecified = true; - sidecar.BlockMedia[0].Heads = heads; - sidecar.BlockMedia[0].HeadsSpecified = true; - sidecar.BlockMedia[0].SectorsPerTrack = sectors; - sidecar.BlockMedia[0].SectorsPerTrackSpecified = true; - } - - DicConsole.WriteLine(); - - DicConsole.WriteLine("Took a total of {0:F3} seconds ({1:F3} processing commands, {2:F3} checksumming).", (end - start).TotalSeconds, totalDuration / 1000, totalChkDuration / 1000); - DicConsole.WriteLine("Avegare speed: {0:F3} MiB/sec.", (((double)blockSize * (double)(blocks + 1)) / 1048576) / (totalDuration / 1000)); - DicConsole.WriteLine("Fastest speed burst: {0:F3} MiB/sec.", maxSpeed); - DicConsole.WriteLine("Slowest speed burst: {0:F3} MiB/sec.", minSpeed); - DicConsole.WriteLine("{0} sectors could not be read.", unreadableSectors.Count); - if(unreadableSectors.Count > 0) - { - unreadableSectors.Sort(); - foreach(ulong bad in unreadableSectors) - DicConsole.WriteLine("Sector {0} could not be read", bad); - } - DicConsole.WriteLine(); - - if(!aborted) - { - DicConsole.WriteLine("Writing metadata sidecar"); - - FileStream xmlFs = new FileStream(options.OutputPrefix + ".cicm.xml", - FileMode.Create); - - System.Xml.Serialization.XmlSerializer xmlSer = new System.Xml.Serialization.XmlSerializer(typeof(CICMMetadataType)); - xmlSer.Serialize(xmlFs, sidecar); - xmlFs.Close(); - } - - Core.Statistics.AddMedia(MediaType.GENERIC_HDD, true); - } - else - DicConsole.ErrorWriteLine("Unable to communicate with ATA device."); - } - - static void doNVMeMediaScan(DumpMediaOptions options, Device dev) - { - throw new NotImplementedException("NVMe devices not yet supported."); - } - - static void doSDMediaScan(DumpMediaOptions options, Device dev) - { - throw new NotImplementedException("MMC/SD devices not yet supported."); - } - - // TODO: Get cartridge serial number from Certance vendor EVPD - static void doSCSIMediaScan(DumpMediaOptions options, Device dev) - { - byte[] cmdBuf = null; - byte[] senseBuf = null; - bool sense = false; - double duration; - ulong blocks = 0; - uint blockSize = 0; - byte[] tmpBuf; - MediaType dskType = MediaType.Unknown; - bool opticalDisc = false; - uint logicalBlockSize = 0; - uint physicalBlockSize = 0; - - if(dev.IsRemovable) - { - sense = dev.ScsiTestUnitReady(out senseBuf, dev.Timeout, out duration); - if(sense) - { - Decoders.SCSI.FixedSense? decSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf); - if(decSense.HasValue) - { - if(decSense.Value.ASC == 0x3A) - { - int leftRetries = 5; - while(leftRetries > 0) - { - DicConsole.WriteLine("\rWaiting for drive to become ready"); - System.Threading.Thread.Sleep(2000); - sense = dev.ScsiTestUnitReady(out senseBuf, dev.Timeout, out duration); - if(!sense) - break; - - leftRetries--; - } - - if(sense) - { - DicConsole.ErrorWriteLine("Please insert media in drive"); - return; - } - } - else if(decSense.Value.ASC == 0x04 && decSense.Value.ASCQ == 0x01) - { - int leftRetries = 10; - while(leftRetries > 0) - { - DicConsole.WriteLine("\rWaiting for drive to become ready"); - System.Threading.Thread.Sleep(2000); - sense = dev.ScsiTestUnitReady(out senseBuf, dev.Timeout, out duration); - if(!sense) - break; - - leftRetries--; - } - - if(sense) - { - DicConsole.ErrorWriteLine("Error testing unit was ready:\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); - return; - } - } - /*else if (decSense.Value.ASC == 0x29 && decSense.Value.ASCQ == 0x00) - { - if (!deviceReset) - { - deviceReset = true; - DicConsole.ErrorWriteLine("Device did reset, retrying..."); - goto retryTestReady; - } - - DicConsole.ErrorWriteLine("Error testing unit was ready:\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); - return; - }*/ - else - { - DicConsole.ErrorWriteLine("Error testing unit was ready:\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); - return; - } - } - else - { - DicConsole.ErrorWriteLine("Unknown testing unit was ready."); - return; - } - } - } - - if(dev.SCSIType == Decoders.SCSI.PeripheralDeviceTypes.DirectAccess || - dev.SCSIType == Decoders.SCSI.PeripheralDeviceTypes.MultiMediaDevice || - dev.SCSIType == Decoders.SCSI.PeripheralDeviceTypes.OCRWDevice || - dev.SCSIType == Decoders.SCSI.PeripheralDeviceTypes.OpticalDevice || - dev.SCSIType == Decoders.SCSI.PeripheralDeviceTypes.SimplifiedDevice || - dev.SCSIType == Decoders.SCSI.PeripheralDeviceTypes.WriteOnceDevice) - { - sense = dev.ReadCapacity(out cmdBuf, out senseBuf, dev.Timeout, out duration); - if(!sense) - { - blocks = (ulong)((cmdBuf[0] << 24) + (cmdBuf[1] << 16) + (cmdBuf[2] << 8) + (cmdBuf[3])); - blockSize = (uint)((cmdBuf[5] << 24) + (cmdBuf[5] << 16) + (cmdBuf[6] << 8) + (cmdBuf[7])); - } - - if(sense || blocks == 0xFFFFFFFF) - { - sense = dev.ReadCapacity16(out cmdBuf, out senseBuf, dev.Timeout, out duration); - - if(sense && blocks == 0) - { - // Not all MMC devices support READ CAPACITY, as they have READ TOC - if(dev.SCSIType != Decoders.SCSI.PeripheralDeviceTypes.MultiMediaDevice) - { - DicConsole.ErrorWriteLine("Unable to get media capacity"); - DicConsole.ErrorWriteLine("{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); - } - } - - if(!sense) - { - byte[] temp = new byte[8]; - - Array.Copy(cmdBuf, 0, temp, 0, 8); - Array.Reverse(temp); - blocks = BitConverter.ToUInt64(temp, 0); - blockSize = (uint)((cmdBuf[5] << 24) + (cmdBuf[5] << 16) + (cmdBuf[6] << 8) + (cmdBuf[7])); - } - } - - if(blocks != 0 && blockSize != 0) - { - blocks++; - DicConsole.WriteLine("Media has {0} blocks of {1} bytes/each. (for a total of {2} bytes)", - blocks, blockSize, blocks * (ulong)blockSize); - } - - logicalBlockSize = blockSize; - physicalBlockSize = blockSize; - } - - DateTime start; - DateTime end; - double totalDuration = 0; - double totalChkDuration = 0; - double currentSpeed = 0; - double maxSpeed = double.MinValue; - double minSpeed = double.MaxValue; - List unreadableSectors = new List(); - Core.Checksum dataChk; - CICMMetadataType sidecar = new CICMMetadataType(); - - if(dev.SCSIType == Decoders.SCSI.PeripheralDeviceTypes.SequentialAccess) - { - if(options.Raw) - throw new ArgumentException("Tapes cannot be dumped raw."); - - Decoders.SCSI.FixedSense? fxSense; - string strSense; - byte[] tapeBuf; - - dev.RequestSense(out senseBuf, dev.Timeout, out duration); - fxSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf, out strSense); - - if(fxSense.HasValue && fxSense.Value.SenseKey != Decoders.SCSI.SenseKeys.NoSense) - { - DicConsole.ErrorWriteLine("Drive has status error, please correct. Sense follows..."); - DicConsole.ErrorWriteLine("{0}", strSense); - return; - } - - // Not in BOM/P - if(fxSense.HasValue && fxSense.Value.ASC == 0x00 && fxSense.Value.ASCQ != 0x04) - { - DicConsole.Write("Rewinding, please wait..."); - // Rewind, let timeout apply - sense = dev.Rewind(out senseBuf, dev.Timeout, out duration); - - // Still rewinding? - // TODO: Pause? - do - { - DicConsole.Write("\rRewinding, please wait..."); - dev.RequestSense(out senseBuf, dev.Timeout, out duration); - fxSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf, out strSense); - } - while(fxSense.HasValue && fxSense.Value.ASC == 0x00 && (fxSense.Value.ASCQ == 0x1A || fxSense.Value.ASCQ != 0x04)); - - dev.RequestSense(out senseBuf, dev.Timeout, out duration); - fxSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf, out strSense); - - // And yet, did not rewind! - if(fxSense.HasValue && ((fxSense.Value.ASC == 0x00 && fxSense.Value.ASCQ != 0x04) || fxSense.Value.ASC != 0x00)) - { - DicConsole.WriteLine(); - DicConsole.ErrorWriteLine("Drive could not rewind, please correct. Sense follows..."); - DicConsole.ErrorWriteLine("{0}", strSense); - return; - } - - DicConsole.WriteLine(); - } - - // Check position - sense = dev.ReadPosition(out tapeBuf, out senseBuf, SscPositionForms.Short, dev.Timeout, out duration); - - if(sense) - { - // READ POSITION is mandatory starting SCSI-2, so do not cry if the drive does not recognize the command (SCSI-1 or earlier) - // Anyway, <=SCSI-1 tapes do not support partitions - fxSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf, out strSense); - if(fxSense.HasValue && ((fxSense.Value.ASC == 0x20 && fxSense.Value.ASCQ != 0x00) || fxSense.Value.ASC != 0x20)) - { - DicConsole.ErrorWriteLine("Could not get position. Sense follows..."); - DicConsole.ErrorWriteLine("{0}", strSense); - return; - } - } - else - { - // Not in partition 0 - if(tapeBuf[1] != 0) - { - DicConsole.Write("Drive not in partition 0. Rewinding, please wait..."); - // Rewind, let timeout apply - sense = dev.Locate(out senseBuf, false, 0, 0, dev.Timeout, out duration); - if(sense) - { - DicConsole.WriteLine(); - DicConsole.ErrorWriteLine("Drive could not rewind, please correct. Sense follows..."); - DicConsole.ErrorWriteLine("{0}", strSense); - return; - } - - // Still rewinding? - // TODO: Pause? - do - { - System.Threading.Thread.Sleep(1000); - DicConsole.Write("\rRewinding, please wait..."); - dev.RequestSense(out senseBuf, dev.Timeout, out duration); - fxSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf, out strSense); - } - while(fxSense.HasValue && fxSense.Value.ASC == 0x00 && (fxSense.Value.ASCQ == 0x1A || fxSense.Value.ASCQ == 0x19)); - - // And yet, did not rewind! - if(fxSense.HasValue && ((fxSense.Value.ASC == 0x00 && fxSense.Value.ASCQ != 0x04) || fxSense.Value.ASC != 0x00)) - { - DicConsole.WriteLine(); - DicConsole.ErrorWriteLine("Drive could not rewind, please correct. Sense follows..."); - DicConsole.ErrorWriteLine("{0}", strSense); - return; - } - - sense = dev.ReadPosition(out tapeBuf, out senseBuf, SscPositionForms.Short, dev.Timeout, out duration); - if(sense) - { - fxSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf, out strSense); - DicConsole.ErrorWriteLine("Drive could not rewind, please correct. Sense follows..."); - DicConsole.ErrorWriteLine("{0}", strSense); - return; - } - - // Still not in partition 0!!!? - if(tapeBuf[1] != 0) - { - DicConsole.ErrorWriteLine("Drive could not rewind to partition 0 but no error occurred..."); - return; - } - - DicConsole.WriteLine(); - } - } - - sidecar.BlockMedia = new BlockMediaType[1]; - sidecar.BlockMedia[0] = new BlockMediaType(); - sidecar.BlockMedia[0].SCSI = new SCSIType(); - byte scsiMediumTypeTape = 0; - byte scsiDensityCodeTape = 0; - - sense = dev.ModeSense10(out cmdBuf, out senseBuf, false, true, ScsiModeSensePageControl.Current, 0x3F, 0xFF, 5, out duration); - if(!sense || dev.Error) - { - sense = dev.ModeSense10(out cmdBuf, out senseBuf, false, true, ScsiModeSensePageControl.Current, 0x3F, 0x00, 5, out duration); - } - - Decoders.SCSI.Modes.DecodedMode? decMode = null; - - if(!sense && !dev.Error) - { - if(Decoders.SCSI.Modes.DecodeMode10(cmdBuf, dev.SCSIType).HasValue) - { - decMode = Decoders.SCSI.Modes.DecodeMode10(cmdBuf, dev.SCSIType); - sidecar.BlockMedia[0].SCSI.ModeSense10 = new DumpType(); - sidecar.BlockMedia[0].SCSI.ModeSense10.Image = options.OutputPrefix + ".modesense10.bin"; - sidecar.BlockMedia[0].SCSI.ModeSense10.Size = cmdBuf.Length; - sidecar.BlockMedia[0].SCSI.ModeSense10.Checksums = Core.Checksum.GetChecksums(cmdBuf).ToArray(); - writeToFile(sidecar.BlockMedia[0].SCSI.ModeSense10.Image, cmdBuf); - } - } - - sense = dev.ModeSense6(out cmdBuf, out senseBuf, false, ScsiModeSensePageControl.Current, 0x3F, 0x00, 5, out duration); - if(sense || dev.Error) - sense = dev.ModeSense6(out cmdBuf, out senseBuf, false, ScsiModeSensePageControl.Current, 0x3F, 0x00, 5, out duration); - if(sense || dev.Error) - sense = dev.ModeSense(out cmdBuf, out senseBuf, 5, out duration); - - if(!sense && !dev.Error) - { - if(Decoders.SCSI.Modes.DecodeMode6(cmdBuf, dev.SCSIType).HasValue) - { - decMode = Decoders.SCSI.Modes.DecodeMode6(cmdBuf, dev.SCSIType); - sidecar.BlockMedia[0].SCSI.ModeSense = new DumpType(); - sidecar.BlockMedia[0].SCSI.ModeSense.Image = options.OutputPrefix + ".modesense.bin"; - sidecar.BlockMedia[0].SCSI.ModeSense.Size = cmdBuf.Length; - sidecar.BlockMedia[0].SCSI.ModeSense.Checksums = Core.Checksum.GetChecksums(cmdBuf).ToArray(); - writeToFile(sidecar.BlockMedia[0].SCSI.ModeSense.Image, cmdBuf); - } - } - - // TODO: Check partitions page - if(decMode.HasValue) - { - scsiMediumTypeTape = (byte)decMode.Value.Header.MediumType; - if(decMode.Value.Header.BlockDescriptors != null && decMode.Value.Header.BlockDescriptors.Length >= 1) - scsiDensityCodeTape = (byte)decMode.Value.Header.BlockDescriptors[0].Density; - } - - if(dskType == MediaType.Unknown) - dskType = MediaTypeFromSCSI.Get((byte)dev.SCSIType, dev.Manufacturer, dev.Model, scsiMediumTypeTape, scsiDensityCodeTape, blocks, blockSize); - - DicConsole.WriteLine("Media identified as {0}", dskType); - - bool endOfMedia = false; - ulong currentBlock = 0; - ulong currentFile = 0; - byte currentPartition = 0; - byte totalPartitions = 1; // TODO: Handle partitions. - blockSize = 1; - ulong currentSize = 0; - ulong currentPartitionSize = 0; - ulong currentFileSize = 0; - - Core.Checksum partitionChk; - Core.Checksum fileChk; - List partitions = new List(); - List files = new List(); - TapeFileType currentTapeFile = new TapeFileType(); - TapePartitionType currentTapePartition = new TapePartitionType(); - - DicConsole.WriteLine(); - initDataFile(options.OutputPrefix + ".bin"); - dataChk = new Core.Checksum(); - start = DateTime.UtcNow; - mhddLog = new MHDDLog(options.OutputPrefix + ".mhddlog.bin", dev, blocks, blockSize, 1); - ibgLog = new IBGLog(options.OutputPrefix + ".ibg", 0x0008); - - currentTapeFile = new TapeFileType(); - currentTapeFile.Image = new ImageType(); - currentTapeFile.Image.format = "BINARY"; - currentTapeFile.Image.offset = (long)currentSize; - currentTapeFile.Image.offsetSpecified = true; - currentTapeFile.Image.Value = options.OutputPrefix + ".bin"; - currentTapeFile.Sequence = (long)currentFile; - currentTapeFile.StartBlock = (long)currentBlock; - fileChk = new Core.Checksum(); - currentTapePartition = new TapePartitionType(); - currentTapePartition.Image = new ImageType(); - currentTapePartition.Image.format = "BINARY"; - currentTapePartition.Image.offset = (long)currentSize; - currentTapePartition.Image.offsetSpecified = true; - currentTapePartition.Image.Value = options.OutputPrefix + ".bin"; - currentTapePartition.Sequence = (long)currentPartition; - currentTapePartition.StartBlock = (long)currentBlock; - partitionChk = new Core.Checksum(); - - aborted = false; - System.Console.CancelKeyPress += (sender, e) => - { - e.Cancel = aborted = true; - }; - - while(currentPartition < totalPartitions) - { - if(aborted) - break; - - if(endOfMedia) - { - DicConsole.WriteLine(); - DicConsole.WriteLine("Finished partition {0}", currentPartition); - currentTapePartition.File = files.ToArray(); - currentTapePartition.Checksums = partitionChk.End().ToArray(); - currentTapePartition.EndBlock = (long)(currentBlock - 1); - currentTapePartition.Size = (long)currentPartitionSize; - partitions.Add(currentTapePartition); - - currentPartition++; - - if(currentPartition < totalPartitions) - { - currentFile++; - currentTapeFile = new TapeFileType(); - currentTapeFile.Image = new ImageType(); - currentTapeFile.Image.format = "BINARY"; - currentTapeFile.Image.offset = (long)currentSize; - currentTapeFile.Image.offsetSpecified = true; - currentTapeFile.Image.Value = options.OutputPrefix + ".bin"; - currentTapeFile.Sequence = (long)currentFile; - currentTapeFile.StartBlock = (long)currentBlock; - currentFileSize = 0; - fileChk = new Core.Checksum(); - files = new List(); - currentTapePartition = new TapePartitionType(); - currentTapePartition.Image = new ImageType(); - currentTapePartition.Image.format = "BINARY"; - currentTapePartition.Image.offset = (long)currentSize; - currentTapePartition.Image.offsetSpecified = true; - currentTapePartition.Image.Value = options.OutputPrefix + ".bin"; - currentTapePartition.Sequence = currentPartition; - currentTapePartition.StartBlock = (long)currentBlock; - currentPartitionSize = 0; - partitionChk = new Core.Checksum(); - DicConsole.WriteLine("Seeking to partition {0}", currentPartition); - sense = dev.Locate(out senseBuf, false, currentPartition, 0, dev.Timeout, out duration); - totalDuration += duration; - } - - continue; - } - -#pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator - if(currentSpeed > maxSpeed && currentSpeed != 0) - maxSpeed = currentSpeed; - if(currentSpeed < minSpeed && currentSpeed != 0) - minSpeed = currentSpeed; -#pragma warning restore RECS0018 // Comparison of floating point numbers with equality operator - - DicConsole.Write("\rReading block {0} ({1:F3} MiB/sec.)", currentBlock, currentSpeed); - - sense = dev.Read6(out tapeBuf, out senseBuf, false, blockSize, blockSize, dev.Timeout, out duration); - totalDuration += duration; - - if(sense) - { - fxSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf, out strSense); - if(fxSense.Value.ASC == 0x00 && fxSense.Value.ASCQ == 0x00 && fxSense.Value.ILI && fxSense.Value.InformationValid) - { - blockSize = (uint)((int)blockSize - BitConverter.ToInt32(BitConverter.GetBytes(fxSense.Value.Information), 0)); - - DicConsole.WriteLine(); - DicConsole.WriteLine("Blocksize changed to {0} bytes at block {1}", blockSize, currentBlock); - - sense = dev.Space(out senseBuf, SscSpaceCodes.LogicalBlock, -1, dev.Timeout, out duration); - totalDuration += duration; - - if(sense) - { - fxSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf, out strSense); - DicConsole.WriteLine(); - DicConsole.ErrorWriteLine("Drive could not go back one block. Sense follows..."); - DicConsole.ErrorWriteLine("{0}", strSense); - closeDataFile(); - return; - } - - continue; - } - - if(fxSense.Value.SenseKey == Decoders.SCSI.SenseKeys.BlankCheck) - { - if(currentBlock == 0) - { - DicConsole.WriteLine(); - DicConsole.ErrorWriteLine("Cannot dump a blank tape..."); - closeDataFile(); - return; - } - - // For sure this is an end-of-tape/partition - if(fxSense.Value.ASC == 0x00 && (fxSense.Value.ASCQ == 0x02 || fxSense.Value.ASCQ == 0x05)) - { - // TODO: Detect end of partition - endOfMedia = true; - continue; - } - - DicConsole.WriteLine(); - DicConsole.WriteLine("Blank block found, end of tape?"); - endOfMedia = true; - continue; - } - - if((fxSense.Value.SenseKey == Decoders.SCSI.SenseKeys.NoSense || fxSense.Value.SenseKey == Decoders.SCSI.SenseKeys.RecoveredError) && - (fxSense.Value.ASCQ == 0x02 || fxSense.Value.ASCQ == 0x05)) - { - // TODO: Detect end of partition - endOfMedia = true; - continue; - } - - if((fxSense.Value.SenseKey == Decoders.SCSI.SenseKeys.NoSense || fxSense.Value.SenseKey == Decoders.SCSI.SenseKeys.RecoveredError) && - fxSense.Value.ASCQ == 0x01) - { - currentTapeFile.Checksums = fileChk.End().ToArray(); - currentTapeFile.EndBlock = (long)(currentBlock - 1); - currentTapeFile.Size = (long)currentFileSize; - files.Add(currentTapeFile); - - currentFile++; - currentTapeFile = new TapeFileType(); - currentTapeFile.Image = new ImageType(); - currentTapeFile.Image.format = "BINARY"; - currentTapeFile.Image.offset = (long)currentSize; - currentTapeFile.Image.offsetSpecified = true; - currentTapeFile.Image.Value = options.OutputPrefix + ".bin"; - currentTapeFile.Sequence = (long)currentFile; - currentTapeFile.StartBlock = (long)currentBlock; - currentFileSize = 0; - fileChk = new Core.Checksum(); - - DicConsole.WriteLine(); - DicConsole.WriteLine("Changed to file {0} at block {1}", currentFile, currentBlock); - continue; - } - - // TODO: Add error recovering for tapes - fxSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf, out strSense); - DicConsole.ErrorWriteLine("Drive could not read block. Sense follows..."); - DicConsole.ErrorWriteLine("{0}", strSense); - return; - } - - mhddLog.Write(currentBlock, duration); - ibgLog.Write(currentBlock, currentSpeed * 1024); - writeToDataFile(tapeBuf); - - DateTime chkStart = DateTime.UtcNow; - dataChk.Update(tapeBuf); - fileChk.Update(tapeBuf); - partitionChk.Update(tapeBuf); - DateTime chkEnd = DateTime.UtcNow; - double chkDuration = (chkEnd - chkStart).TotalMilliseconds; - totalChkDuration += chkDuration; - - if(currentBlock % 10 == 0) - currentSpeed = ((double)2448 / (double)1048576) / (duration / (double)1000); - currentBlock++; - currentSize += blockSize; - currentFileSize += blockSize; - currentPartitionSize += blockSize; - } - - blocks = currentBlock + 1; - DicConsole.WriteLine(); - end = DateTime.UtcNow; - mhddLog.Close(); - ibgLog.Close(dev, blocks, blockSize, (end - start).TotalSeconds, currentSpeed * 1024, (((double)blockSize * (double)(blocks + 1)) / 1024) / (totalDuration / 1000), options.DevicePath); - - DicConsole.WriteLine("Took a total of {0:F3} seconds ({1:F3} processing commands, {2:F3} checksumming).", (end - start).TotalSeconds, totalDuration / 1000, totalChkDuration / 1000); -#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created - DicConsole.WriteLine("Avegare speed: {0:F3} MiB/sec.", (((double)blockSize * (double)(blocks + 1)) / 1048576) / (totalDuration / 1000)); -#pragma warning restore IDE0004 // Cast is necessary, otherwise incorrect value is created - DicConsole.WriteLine("Fastest speed burst: {0:F3} MiB/sec.", maxSpeed); - DicConsole.WriteLine("Slowest speed burst: {0:F3} MiB/sec.", minSpeed); - - sidecar.BlockMedia[0].Checksums = dataChk.End().ToArray(); - sidecar.BlockMedia[0].Dimensions = Metadata.Dimensions.DimensionsFromMediaType(dskType); - string xmlDskTyp, xmlDskSubTyp; - Metadata.MediaType.MediaTypeToString(dskType, out xmlDskTyp, out xmlDskSubTyp); - sidecar.BlockMedia[0].DiskType = xmlDskTyp; - sidecar.BlockMedia[0].DiskSubType = xmlDskSubTyp; - // TODO: Implement device firmware revision - sidecar.BlockMedia[0].Image = new ImageType(); - sidecar.BlockMedia[0].Image.format = "Raw disk image (sector by sector copy)"; - sidecar.BlockMedia[0].Image.Value = options.OutputPrefix + ".bin"; - sidecar.BlockMedia[0].LogicalBlocks = (long)blocks; - sidecar.BlockMedia[0].Size = (long)(currentSize); - sidecar.BlockMedia[0].DumpHardwareArray = new DumpHardwareType[1]; - sidecar.BlockMedia[0].DumpHardwareArray[0] = new DumpHardwareType(); - sidecar.BlockMedia[0].DumpHardwareArray[0].Extents = new ExtentType[1]; - sidecar.BlockMedia[0].DumpHardwareArray[0].Extents[0] = new ExtentType(); - sidecar.BlockMedia[0].DumpHardwareArray[0].Extents[0].Start = 0; - sidecar.BlockMedia[0].DumpHardwareArray[0].Extents[0].End = (int)(blocks - 1); - sidecar.BlockMedia[0].DumpHardwareArray[0].Manufacturer = dev.Manufacturer; - sidecar.BlockMedia[0].DumpHardwareArray[0].Model = dev.Model; - sidecar.BlockMedia[0].DumpHardwareArray[0].Revision = dev.Revision; - sidecar.BlockMedia[0].DumpHardwareArray[0].Serial = dev.Serial; - sidecar.BlockMedia[0].DumpHardwareArray[0].Software = new SoftwareType(); - sidecar.BlockMedia[0].DumpHardwareArray[0].Software.Name = "DiscImageChef"; - sidecar.BlockMedia[0].DumpHardwareArray[0].Software.OperatingSystem = dev.PlatformID.ToString(); - sidecar.BlockMedia[0].DumpHardwareArray[0].Software.Version = typeof(MainClass).Assembly.GetName().Version.ToString(); - sidecar.BlockMedia[0].TapeInformation = partitions.ToArray(); - - if(!aborted) - { - DicConsole.WriteLine("Writing metadata sidecar"); - - FileStream xmlFs = new FileStream(options.OutputPrefix + ".cicm.xml", - FileMode.Create); - - System.Xml.Serialization.XmlSerializer xmlSer = new System.Xml.Serialization.XmlSerializer(typeof(CICMMetadataType)); - xmlSer.Serialize(xmlFs, sidecar); - xmlFs.Close(); - } - - Core.Statistics.AddMedia(dskType, true); - - return; - } - - if(blocks == 0) - { - DicConsole.ErrorWriteLine("Unable to read medium or empty medium present..."); - return; - } - - bool compactDisc = true; - Decoders.CD.FullTOC.CDFullTOC? toc = null; - byte scsiMediumType = 0; - byte scsiDensityCode = 0; - bool containsFloppyPage = false; - ushort currentProfile = 0x0001; - bool isXbox = false; - - #region MultiMediaDevice - if(dev.SCSIType == Decoders.SCSI.PeripheralDeviceTypes.MultiMediaDevice) - { - sidecar.OpticalDisc = new OpticalDiscType[1]; - sidecar.OpticalDisc[0] = new OpticalDiscType(); - opticalDisc = true; - - sense = dev.GetConfiguration(out cmdBuf, out senseBuf, 0, MmcGetConfigurationRt.Current, dev.Timeout, out duration); - if(!sense) - { - Decoders.SCSI.MMC.Features.SeparatedFeatures ftr = Decoders.SCSI.MMC.Features.Separate(cmdBuf); - currentProfile = ftr.CurrentProfile; - - switch(ftr.CurrentProfile) - { - case 0x0001: - dskType = MediaType.GENERIC_HDD; - goto default; - case 0x0005: - dskType = MediaType.CDMO; - break; - case 0x0008: - dskType = MediaType.CD; - break; - case 0x0009: - dskType = MediaType.CDR; - break; - case 0x000A: - dskType = MediaType.CDRW; - break; - case 0x0010: - dskType = MediaType.DVDROM; - goto default; - case 0x0011: - dskType = MediaType.DVDR; - goto default; - case 0x0012: - dskType = MediaType.DVDRAM; - goto default; - case 0x0013: - case 0x0014: - dskType = MediaType.DVDRW; - goto default; - case 0x0015: - case 0x0016: - dskType = MediaType.DVDRDL; - goto default; - case 0x0017: - dskType = MediaType.DVDRWDL; - goto default; - case 0x0018: - dskType = MediaType.DVDDownload; - goto default; - case 0x001A: - dskType = MediaType.DVDPRW; - goto default; - case 0x001B: - dskType = MediaType.DVDPR; - goto default; - case 0x0020: - dskType = MediaType.DDCD; - goto default; - case 0x0021: - dskType = MediaType.DDCDR; - goto default; - case 0x0022: - dskType = MediaType.DDCDRW; - goto default; - case 0x002A: - dskType = MediaType.DVDPRWDL; - goto default; - case 0x002B: - dskType = MediaType.DVDPRDL; - goto default; - case 0x0040: - dskType = MediaType.BDROM; - goto default; - case 0x0041: - case 0x0042: - dskType = MediaType.BDR; - goto default; - case 0x0043: - dskType = MediaType.BDRE; - goto default; - case 0x0050: - dskType = MediaType.HDDVDROM; - goto default; - case 0x0051: - dskType = MediaType.HDDVDR; - goto default; - case 0x0052: - dskType = MediaType.HDDVDRAM; - goto default; - case 0x0053: - dskType = MediaType.HDDVDRW; - goto default; - case 0x0058: - dskType = MediaType.HDDVDRDL; - goto default; - case 0x005A: - dskType = MediaType.HDDVDRWDL; - goto default; - default: - compactDisc = false; - break; - } - } - - #region CompactDisc - if(compactDisc) - { - // We discarded all discs that falsify a TOC before requesting a real TOC - // No TOC, no CD (or an empty one) - bool tocSense = dev.ReadRawToc(out cmdBuf, out senseBuf, 1, dev.Timeout, out duration); - if(!tocSense) - { - toc = Decoders.CD.FullTOC.Decode(cmdBuf); - if(toc.HasValue) - { - tmpBuf = new byte[cmdBuf.Length - 2]; - Array.Copy(cmdBuf, 2, tmpBuf, 0, cmdBuf.Length - 2); - sidecar.OpticalDisc[0].TOC = new DumpType(); - sidecar.OpticalDisc[0].TOC.Image = options.OutputPrefix + ".toc.bin"; - sidecar.OpticalDisc[0].TOC.Size = tmpBuf.Length; - sidecar.OpticalDisc[0].TOC.Checksums = Core.Checksum.GetChecksums(tmpBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].TOC.Image, tmpBuf); - - // ATIP exists on blank CDs - sense = dev.ReadAtip(out cmdBuf, out senseBuf, dev.Timeout, out duration); - if(!sense) - { - Decoders.CD.ATIP.CDATIP? atip = Decoders.CD.ATIP.Decode(cmdBuf); - if(atip.HasValue) - { - if(blocks == 0) - { - DicConsole.ErrorWriteLine("Cannot dump blank media."); - return; - } - - // Only CD-R and CD-RW have ATIP - dskType = atip.Value.DiscType ? MediaType.CDRW : MediaType.CDR; - - tmpBuf = new byte[cmdBuf.Length - 4]; - Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); - sidecar.OpticalDisc[0].ATIP = new DumpType(); - sidecar.OpticalDisc[0].ATIP.Image = options.OutputPrefix + ".atip.bin"; - sidecar.OpticalDisc[0].ATIP.Size = tmpBuf.Length; - sidecar.OpticalDisc[0].ATIP.Checksums = Core.Checksum.GetChecksums(tmpBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].TOC.Image, tmpBuf); - } - } - - sense = dev.ReadDiscInformation(out cmdBuf, out senseBuf, MmcDiscInformationDataTypes.DiscInformation, dev.Timeout, out duration); - if(!sense) - { - Decoders.SCSI.MMC.DiscInformation.StandardDiscInformation? discInfo = Decoders.SCSI.MMC.DiscInformation.Decode000b(cmdBuf); - if(discInfo.HasValue) - { - // If it is a read-only CD, check CD type if available - if(dskType == MediaType.CD) - { - switch(discInfo.Value.DiscType) - { - case 0x10: - dskType = MediaType.CDI; - break; - case 0x20: - dskType = MediaType.CDROMXA; - break; - } - } - } - } - - int sessions = 1; - int firstTrackLastSession = 0; - - sense = dev.ReadSessionInfo(out cmdBuf, out senseBuf, dev.Timeout, out duration); - if(!sense) - { - Decoders.CD.Session.CDSessionInfo? session = Decoders.CD.Session.Decode(cmdBuf); - if(session.HasValue) - { - sessions = session.Value.LastCompleteSession; - firstTrackLastSession = session.Value.TrackDescriptors[0].TrackNumber; - } - } - - if(dskType == MediaType.CD) - { - bool hasDataTrack = false; - bool hasAudioTrack = false; - bool allFirstSessionTracksAreAudio = true; - bool hasVideoTrack = false; - - if(toc.HasValue) - { - foreach(Decoders.CD.FullTOC.TrackDataDescriptor track in toc.Value.TrackDescriptors) - { - if(track.TNO == 1 && - ((Decoders.CD.TOC_CONTROL)(track.CONTROL & 0x0D) == Decoders.CD.TOC_CONTROL.DataTrack || - (Decoders.CD.TOC_CONTROL)(track.CONTROL & 0x0D) == Decoders.CD.TOC_CONTROL.DataTrackIncremental)) - { - allFirstSessionTracksAreAudio &= firstTrackLastSession != 1; - } - - if((Decoders.CD.TOC_CONTROL)(track.CONTROL & 0x0D) == Decoders.CD.TOC_CONTROL.DataTrack || - (Decoders.CD.TOC_CONTROL)(track.CONTROL & 0x0D) == Decoders.CD.TOC_CONTROL.DataTrackIncremental) - { - hasDataTrack = true; - allFirstSessionTracksAreAudio &= track.TNO >= firstTrackLastSession; - } - else - hasAudioTrack = true; - - hasVideoTrack |= track.ADR == 4; - } - } - - if(hasDataTrack && hasAudioTrack && allFirstSessionTracksAreAudio && sessions == 2) - dskType = MediaType.CDPLUS; - if(!hasDataTrack && hasAudioTrack && sessions == 1) - dskType = MediaType.CDDA; - if(hasDataTrack && !hasAudioTrack && sessions == 1) - dskType = MediaType.CDROM; - if(hasVideoTrack && !hasDataTrack && sessions == 1) - dskType = MediaType.CDV; - } - - sense = dev.ReadPma(out cmdBuf, out senseBuf, dev.Timeout, out duration); - if(!sense) - { - if(Decoders.CD.PMA.Decode(cmdBuf).HasValue) - { - tmpBuf = new byte[cmdBuf.Length - 4]; - Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); - sidecar.OpticalDisc[0].PMA = new DumpType(); - sidecar.OpticalDisc[0].PMA.Image = options.OutputPrefix + ".pma.bin"; - sidecar.OpticalDisc[0].PMA.Size = tmpBuf.Length; - sidecar.OpticalDisc[0].PMA.Checksums = Core.Checksum.GetChecksums(tmpBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].PMA.Image, tmpBuf); - } - } - - sense = dev.ReadCdText(out cmdBuf, out senseBuf, dev.Timeout, out duration); - if(!sense) - { - if(Decoders.CD.CDTextOnLeadIn.Decode(cmdBuf).HasValue) - { - tmpBuf = new byte[cmdBuf.Length - 4]; - Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); - sidecar.OpticalDisc[0].LeadInCdText = new DumpType(); - sidecar.OpticalDisc[0].LeadInCdText.Image = options.OutputPrefix + ".cdtext.bin"; - sidecar.OpticalDisc[0].LeadInCdText.Size = tmpBuf.Length; - sidecar.OpticalDisc[0].LeadInCdText.Checksums = Core.Checksum.GetChecksums(tmpBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].LeadInCdText.Image, tmpBuf); - } - } - } - } - - physicalBlockSize = 2448; - } - #endregion CompactDisc - else - { - #region Nintendo - if(dskType == MediaType.Unknown && blocks > 0) - { - sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.PhysicalInformation, 0, dev.Timeout, out duration); - if(!sense) - { - Decoders.DVD.PFI.PhysicalFormatInformation? nintendoPfi = Decoders.DVD.PFI.Decode(cmdBuf); - if(nintendoPfi != null) - { - if(nintendoPfi.Value.DiskCategory == Decoders.DVD.DiskCategory.Nintendo && - nintendoPfi.Value.PartVersion == 15) - { - throw new NotImplementedException("Dumping Nintendo GameCube or Wii discs is not yet implemented."); - } - } - } - } - #endregion Nintendo - - #region All DVD and HD DVD types - if(dskType == MediaType.DVDDownload || dskType == MediaType.DVDPR || - dskType == MediaType.DVDPRDL || dskType == MediaType.DVDPRW || - dskType == MediaType.DVDPRWDL || dskType == MediaType.DVDR || - dskType == MediaType.DVDRAM || dskType == MediaType.DVDRDL || - dskType == MediaType.DVDROM || dskType == MediaType.DVDRW || - dskType == MediaType.DVDRWDL || dskType == MediaType.HDDVDR || - dskType == MediaType.HDDVDRAM || dskType == MediaType.HDDVDRDL || - dskType == MediaType.HDDVDROM || dskType == MediaType.HDDVDRW || - dskType == MediaType.HDDVDRWDL) - { - - sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.PhysicalInformation, 0, dev.Timeout, out duration); - if(!sense) - { - if(Decoders.DVD.PFI.Decode(cmdBuf).HasValue) - { - tmpBuf = new byte[cmdBuf.Length - 4]; - Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); - sidecar.OpticalDisc[0].PFI = new DumpType(); - sidecar.OpticalDisc[0].PFI.Image = options.OutputPrefix + ".pfi.bin"; - sidecar.OpticalDisc[0].PFI.Size = tmpBuf.Length; - sidecar.OpticalDisc[0].PFI.Checksums = Core.Checksum.GetChecksums(tmpBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].PFI.Image, tmpBuf); - - Decoders.DVD.PFI.PhysicalFormatInformation decPfi = Decoders.DVD.PFI.Decode(cmdBuf).Value; - DicConsole.WriteLine("PFI:\n{0}", Decoders.DVD.PFI.Prettify(decPfi)); - - // False book types - if(dskType == MediaType.DVDROM) - { - switch(decPfi.DiskCategory) - { - case Decoders.DVD.DiskCategory.DVDPR: - dskType = MediaType.DVDPR; - break; - case Decoders.DVD.DiskCategory.DVDPRDL: - dskType = MediaType.DVDPRDL; - break; - case Decoders.DVD.DiskCategory.DVDPRW: - dskType = MediaType.DVDPRW; - break; - case Decoders.DVD.DiskCategory.DVDPRWDL: - dskType = MediaType.DVDPRWDL; - break; - case Decoders.DVD.DiskCategory.DVDR: - if(decPfi.PartVersion == 6) - dskType = MediaType.DVDRDL; - else - dskType = MediaType.DVDR; - break; - case Decoders.DVD.DiskCategory.DVDRAM: - dskType = MediaType.DVDRAM; - break; - default: - dskType = MediaType.DVDROM; - break; - case Decoders.DVD.DiskCategory.DVDRW: - if(decPfi.PartVersion == 3) - dskType = MediaType.DVDRWDL; - else - dskType = MediaType.DVDRW; - break; - case Decoders.DVD.DiskCategory.HDDVDR: - dskType = MediaType.HDDVDR; - break; - case Decoders.DVD.DiskCategory.HDDVDRAM: - dskType = MediaType.HDDVDRAM; - break; - case Decoders.DVD.DiskCategory.HDDVDROM: - dskType = MediaType.HDDVDROM; - break; - case Decoders.DVD.DiskCategory.HDDVDRW: - dskType = MediaType.HDDVDRW; - break; - case Decoders.DVD.DiskCategory.Nintendo: - if(decPfi.DiscSize == Decoders.DVD.DVDSize.Eighty) - dskType = MediaType.GOD; - else - dskType = MediaType.WOD; - break; - case Decoders.DVD.DiskCategory.UMD: - dskType = MediaType.UMD; - break; - } - } - } - } - sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.DiscManufacturingInformation, 0, dev.Timeout, out duration); - if(!sense) - { - if(Decoders.Xbox.DMI.IsXbox(cmdBuf) || Decoders.Xbox.DMI.IsXbox360(cmdBuf)) - { - if(Decoders.Xbox.DMI.IsXbox(cmdBuf)) - dskType = MediaType.XGD; - else if(Decoders.Xbox.DMI.IsXbox360(cmdBuf)) - { - dskType = MediaType.XGD2; - - // All XGD3 all have the same number of blocks - if(blocks == 25063 || // Locked (or non compatible drive) - blocks == 4229664 || // Xtreme unlock - blocks == 4246304) // Wxripper unlock - dskType = MediaType.XGD3; - } - - byte[] inqBuf; - sense = dev.ScsiInquiry(out inqBuf, out senseBuf); - - if(sense || !Decoders.SCSI.Inquiry.Decode(inqBuf).HasValue || - (Decoders.SCSI.Inquiry.Decode(inqBuf).HasValue && !Decoders.SCSI.Inquiry.Decode(inqBuf).Value.KreonPresent)) - throw new NotImplementedException("Dumping Xbox Game Discs requires a drive with Kreon firmware."); - - if(options.Raw && !options.Force) - { - DicConsole.ErrorWriteLine("Not continuing. If you want to continue reading cooked data when raw is not available use the force option."); - // TODO: Exit more gracefully - return; - } - - isXbox = true; - } - - if(cmdBuf.Length == 2052) - { - tmpBuf = new byte[cmdBuf.Length - 4]; - Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); - sidecar.OpticalDisc[0].DMI = new DumpType(); - sidecar.OpticalDisc[0].DMI.Image = options.OutputPrefix + ".dmi.bin"; - sidecar.OpticalDisc[0].DMI.Size = tmpBuf.Length; - sidecar.OpticalDisc[0].DMI.Checksums = Core.Checksum.GetChecksums(tmpBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].DMI.Image, tmpBuf); - } - } - } - #endregion All DVD and HD DVD types - - #region DVD-ROM - if(dskType == MediaType.DVDDownload || dskType == MediaType.DVDROM) - { - sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.CopyrightInformation, 0, dev.Timeout, out duration); - if(!sense) - { - if(Decoders.DVD.CSS_CPRM.DecodeLeadInCopyright(cmdBuf).HasValue) - { - tmpBuf = new byte[cmdBuf.Length - 4]; - Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); - sidecar.OpticalDisc[0].CMI = new DumpType(); - sidecar.OpticalDisc[0].CMI.Image = options.OutputPrefix + ".cmi.bin"; - sidecar.OpticalDisc[0].CMI.Size = tmpBuf.Length; - sidecar.OpticalDisc[0].CMI.Checksums = Core.Checksum.GetChecksums(tmpBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].CMI.Image, tmpBuf); - - Decoders.DVD.CSS_CPRM.LeadInCopyright cpy = Decoders.DVD.CSS_CPRM.DecodeLeadInCopyright(cmdBuf).Value; - if(cpy.CopyrightType != Decoders.DVD.CopyrightType.NoProtection) - sidecar.OpticalDisc[0].CopyProtection = cpy.CopyrightType.ToString(); - } - } - } - #endregion DVD-ROM - - #region DVD-ROM and HD DVD-ROM - if(dskType == MediaType.DVDDownload || dskType == MediaType.DVDROM || - dskType == MediaType.HDDVDROM) - { - sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.BurstCuttingArea, 0, dev.Timeout, out duration); - if(!sense) - { - tmpBuf = new byte[cmdBuf.Length - 4]; - Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); - sidecar.OpticalDisc[0].BCA = new DumpType(); - sidecar.OpticalDisc[0].BCA.Image = options.OutputPrefix + ".bca.bin"; - sidecar.OpticalDisc[0].BCA.Size = tmpBuf.Length; - sidecar.OpticalDisc[0].BCA.Checksums = Core.Checksum.GetChecksums(tmpBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].BCA.Image, tmpBuf); - } - } - #endregion DVD-ROM and HD DVD-ROM - - #region DVD-RAM and HD DVD-RAM - if(dskType == MediaType.DVDRAM || dskType == MediaType.HDDVDRAM) - { - sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.DVDRAM_DDS, 0, dev.Timeout, out duration); - if(!sense) - { - if(Decoders.DVD.DDS.Decode(cmdBuf).HasValue) - { - tmpBuf = new byte[cmdBuf.Length - 4]; - Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); - sidecar.OpticalDisc[0].DDS = new DumpType(); - sidecar.OpticalDisc[0].DDS.Image = options.OutputPrefix + ".dds.bin"; - sidecar.OpticalDisc[0].DDS.Size = tmpBuf.Length; - sidecar.OpticalDisc[0].DDS.Checksums = Core.Checksum.GetChecksums(tmpBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].DDS.Image, tmpBuf); - } - } - - sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.DVDRAM_SpareAreaInformation, 0, dev.Timeout, out duration); - if(!sense) - { - if(Decoders.DVD.Spare.Decode(cmdBuf).HasValue) - { - tmpBuf = new byte[cmdBuf.Length - 4]; - Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); - sidecar.OpticalDisc[0].SAI = new DumpType(); - sidecar.OpticalDisc[0].SAI.Image = options.OutputPrefix + ".sai.bin"; - sidecar.OpticalDisc[0].SAI.Size = tmpBuf.Length; - sidecar.OpticalDisc[0].SAI.Checksums = Core.Checksum.GetChecksums(tmpBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].SAI.Image, tmpBuf); - } - } - } - #endregion DVD-RAM and HD DVD-RAM - - #region DVD-R and DVD-RW - if(dskType == MediaType.DVDR || dskType == MediaType.DVDRW) - { - sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.PreRecordedInfo, 0, dev.Timeout, out duration); - if(!sense) - { - tmpBuf = new byte[cmdBuf.Length - 4]; - Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); - sidecar.OpticalDisc[0].PRI = new DumpType(); - sidecar.OpticalDisc[0].PRI.Image = options.OutputPrefix + ".pri.bin"; - sidecar.OpticalDisc[0].PRI.Size = tmpBuf.Length; - sidecar.OpticalDisc[0].PRI.Checksums = Core.Checksum.GetChecksums(tmpBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].SAI.Image, tmpBuf); - } - } - #endregion DVD-R and DVD-RW - - #region DVD-R, DVD-RW and HD DVD-R - if(dskType == MediaType.DVDR || dskType == MediaType.DVDRW || dskType == MediaType.HDDVDR) - { - sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.DVDR_MediaIdentifier, 0, dev.Timeout, out duration); - if(!sense) - { - tmpBuf = new byte[cmdBuf.Length - 4]; - Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); - sidecar.OpticalDisc[0].MediaID = new DumpType(); - sidecar.OpticalDisc[0].MediaID.Image = options.OutputPrefix + ".mid.bin"; - sidecar.OpticalDisc[0].MediaID.Size = tmpBuf.Length; - sidecar.OpticalDisc[0].MediaID.Checksums = Core.Checksum.GetChecksums(tmpBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].MediaID.Image, tmpBuf); - } - - sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.DVDR_PhysicalInformation, 0, dev.Timeout, out duration); - if(!sense) - { - tmpBuf = new byte[cmdBuf.Length - 4]; - Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); - sidecar.OpticalDisc[0].PFIR = new DumpType(); - sidecar.OpticalDisc[0].PFIR.Image = options.OutputPrefix + ".pfir.bin"; - sidecar.OpticalDisc[0].PFIR.Size = tmpBuf.Length; - sidecar.OpticalDisc[0].PFIR.Checksums = Core.Checksum.GetChecksums(tmpBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].PFIR.Image, tmpBuf); - } - } - #endregion DVD-R, DVD-RW and HD DVD-R - - #region All DVD+ - if(dskType == MediaType.DVDPR || dskType == MediaType.DVDPRDL || - dskType == MediaType.DVDPRW || dskType == MediaType.DVDPRWDL) - { - sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.ADIP, 0, dev.Timeout, out duration); - if(!sense) - { - tmpBuf = new byte[cmdBuf.Length - 4]; - Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); - sidecar.OpticalDisc[0].ADIP = new DumpType(); - sidecar.OpticalDisc[0].ADIP.Image = options.OutputPrefix + ".adip.bin"; - sidecar.OpticalDisc[0].ADIP.Size = tmpBuf.Length; - sidecar.OpticalDisc[0].ADIP.Checksums = Core.Checksum.GetChecksums(tmpBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].ADIP.Image, tmpBuf); - } - - sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.DCB, 0, dev.Timeout, out duration); - if(!sense) - { - tmpBuf = new byte[cmdBuf.Length - 4]; - Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); - sidecar.OpticalDisc[0].DCB = new DumpType(); - sidecar.OpticalDisc[0].DCB.Image = options.OutputPrefix + ".dcb.bin"; - sidecar.OpticalDisc[0].DCB.Size = tmpBuf.Length; - sidecar.OpticalDisc[0].DCB.Checksums = Core.Checksum.GetChecksums(tmpBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].DCB.Image, tmpBuf); - } - } - #endregion All DVD+ - - #region HD DVD-ROM - if(dskType == MediaType.HDDVDROM) - { - sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.HDDVD_CopyrightInformation, 0, dev.Timeout, out duration); - if(!sense) - { - tmpBuf = new byte[cmdBuf.Length - 4]; - Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); - sidecar.OpticalDisc[0].CMI = new DumpType(); - sidecar.OpticalDisc[0].CMI.Image = options.OutputPrefix + ".cmi.bin"; - sidecar.OpticalDisc[0].CMI.Size = tmpBuf.Length; - sidecar.OpticalDisc[0].CMI.Checksums = Core.Checksum.GetChecksums(tmpBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].CMI.Image, tmpBuf); - } - } - #endregion HD DVD-ROM - - #region All Blu-ray - if(dskType == MediaType.BDR || dskType == MediaType.BDRE || dskType == MediaType.BDROM || - dskType == MediaType.BDRXL || dskType == MediaType.BDREXL) - { - sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.BD, 0, 0, MmcDiscStructureFormat.DiscInformation, 0, dev.Timeout, out duration); - if(!sense) - { - if(Decoders.Bluray.DI.Decode(cmdBuf).HasValue) - { - tmpBuf = new byte[cmdBuf.Length - 4]; - Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); - sidecar.OpticalDisc[0].DI = new DumpType(); - sidecar.OpticalDisc[0].DI.Image = options.OutputPrefix + ".di.bin"; - sidecar.OpticalDisc[0].DI.Size = tmpBuf.Length; - sidecar.OpticalDisc[0].DI.Checksums = Core.Checksum.GetChecksums(tmpBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].DI.Image, tmpBuf); - } - } - - sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.BD, 0, 0, MmcDiscStructureFormat.PAC, 0, dev.Timeout, out duration); - if(!sense) - { - tmpBuf = new byte[cmdBuf.Length - 4]; - Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); - sidecar.OpticalDisc[0].PAC = new DumpType(); - sidecar.OpticalDisc[0].PAC.Image = options.OutputPrefix + ".pac.bin"; - sidecar.OpticalDisc[0].PAC.Size = tmpBuf.Length; - sidecar.OpticalDisc[0].PAC.Checksums = Core.Checksum.GetChecksums(tmpBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].PAC.Image, tmpBuf); - } - } - #endregion All Blu-ray - - - #region BD-ROM only - if(dskType == MediaType.BDROM) - { - sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.BD, 0, 0, MmcDiscStructureFormat.BD_BurstCuttingArea, 0, dev.Timeout, out duration); - if(!sense) - { - tmpBuf = new byte[cmdBuf.Length - 4]; - Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); - sidecar.OpticalDisc[0].BCA = new DumpType(); - sidecar.OpticalDisc[0].BCA.Image = options.OutputPrefix + ".bca.bin"; - sidecar.OpticalDisc[0].BCA.Size = tmpBuf.Length; - sidecar.OpticalDisc[0].BCA.Checksums = Core.Checksum.GetChecksums(tmpBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].BCA.Image, tmpBuf); - } - } - #endregion BD-ROM only - - #region Writable Blu-ray only - if(dskType == MediaType.BDR || dskType == MediaType.BDRE || - dskType == MediaType.BDRXL || dskType == MediaType.BDREXL) - { - sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.BD, 0, 0, MmcDiscStructureFormat.BD_DDS, 0, dev.Timeout, out duration); - if(!sense) - { - tmpBuf = new byte[cmdBuf.Length - 4]; - Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); - sidecar.OpticalDisc[0].DDS = new DumpType(); - sidecar.OpticalDisc[0].DDS.Image = options.OutputPrefix + ".dds.bin"; - sidecar.OpticalDisc[0].DDS.Size = tmpBuf.Length; - sidecar.OpticalDisc[0].DDS.Checksums = Core.Checksum.GetChecksums(tmpBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].DDS.Image, tmpBuf); - } - - sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.BD, 0, 0, MmcDiscStructureFormat.BD_SpareAreaInformation, 0, dev.Timeout, out duration); - if(!sense) - { - tmpBuf = new byte[cmdBuf.Length - 4]; - Array.Copy(cmdBuf, 4, tmpBuf, 0, cmdBuf.Length - 4); - sidecar.OpticalDisc[0].SAI = new DumpType(); - sidecar.OpticalDisc[0].SAI.Image = options.OutputPrefix + ".sai.bin"; - sidecar.OpticalDisc[0].SAI.Size = tmpBuf.Length; - sidecar.OpticalDisc[0].SAI.Checksums = Core.Checksum.GetChecksums(tmpBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].SAI.Image, tmpBuf); - } - } - #endregion Writable Blu-ray only - } - } - #endregion MultiMediaDevice - else - { - compactDisc = false; - sidecar.BlockMedia = new BlockMediaType[1]; - sidecar.BlockMedia[0] = new BlockMediaType(); - - // All USB flash drives report as removable, even if the media is not removable - if(!dev.IsRemovable || dev.IsUSB) - { - if(dev.IsUSB) - { - sidecar.BlockMedia[0].USB = new USBType(); - sidecar.BlockMedia[0].USB.ProductID = dev.USBProductID; - sidecar.BlockMedia[0].USB.VendorID = dev.USBVendorID; - sidecar.BlockMedia[0].USB.Descriptors = new DumpType(); - sidecar.BlockMedia[0].USB.Descriptors.Image = options.OutputPrefix + ".usbdescriptors.bin"; - sidecar.BlockMedia[0].USB.Descriptors.Size = dev.USBDescriptors.Length; - sidecar.BlockMedia[0].USB.Descriptors.Checksums = Core.Checksum.GetChecksums(dev.USBDescriptors).ToArray(); - writeToFile(sidecar.BlockMedia[0].USB.Descriptors.Image, dev.USBDescriptors); - } - - if(dev.Type == DeviceType.ATAPI) - { - Decoders.ATA.AtaErrorRegistersCHS errorRegs; - sense = dev.AtapiIdentify(out cmdBuf, out errorRegs); - if(!sense) - { - sidecar.BlockMedia[0].ATA = new ATAType(); - sidecar.BlockMedia[0].ATA.Identify = new DumpType(); - sidecar.BlockMedia[0].ATA.Identify.Image = options.OutputPrefix + ".identify.bin"; - sidecar.BlockMedia[0].ATA.Identify.Size = cmdBuf.Length; - sidecar.BlockMedia[0].ATA.Identify.Checksums = Core.Checksum.GetChecksums(cmdBuf).ToArray(); - writeToFile(sidecar.BlockMedia[0].ATA.Identify.Image, cmdBuf); - } - } - - sense = dev.ScsiInquiry(out cmdBuf, out senseBuf); - if(!sense) - { - sidecar.BlockMedia[0].SCSI = new SCSIType(); - sidecar.BlockMedia[0].SCSI.Inquiry = new DumpType(); - sidecar.BlockMedia[0].SCSI.Inquiry.Image = options.OutputPrefix + ".inquiry.bin"; - sidecar.BlockMedia[0].SCSI.Inquiry.Size = cmdBuf.Length; - sidecar.BlockMedia[0].SCSI.Inquiry.Checksums = Core.Checksum.GetChecksums(cmdBuf).ToArray(); - writeToFile(sidecar.BlockMedia[0].SCSI.Inquiry.Image, cmdBuf); - - sense = dev.ScsiInquiry(out cmdBuf, out senseBuf, 0x00); - if(!sense) - { - byte[] pages = Decoders.SCSI.EVPD.DecodePage00(cmdBuf); - - if(pages != null) - { - List evpds = new List(); - foreach(byte page in pages) - { - sense = dev.ScsiInquiry(out cmdBuf, out senseBuf, page); - if(!sense) - { - EVPDType evpd = new EVPDType(); - evpd.Image = string.Format("{0}.evpd_{1:X2}h.bin", options.OutputPrefix, page); - evpd.Checksums = Core.Checksum.GetChecksums(cmdBuf).ToArray(); - evpd.Size = cmdBuf.Length; - evpd.Checksums = Core.Checksum.GetChecksums(cmdBuf).ToArray(); - writeToFile(evpd.Image, cmdBuf); - evpds.Add(evpd); - } - } - - if(evpds.Count > 0) - sidecar.BlockMedia[0].SCSI.EVPD = evpds.ToArray(); - } - } - - sense = dev.ModeSense10(out cmdBuf, out senseBuf, false, true, ScsiModeSensePageControl.Current, 0x3F, 0xFF, 5, out duration); - if(!sense || dev.Error) - { - sense = dev.ModeSense10(out cmdBuf, out senseBuf, false, true, ScsiModeSensePageControl.Current, 0x3F, 0x00, 5, out duration); - } - - Decoders.SCSI.Modes.DecodedMode? decMode = null; - - if(!sense && !dev.Error) - { - if(Decoders.SCSI.Modes.DecodeMode10(cmdBuf, dev.SCSIType).HasValue) - { - decMode = Decoders.SCSI.Modes.DecodeMode10(cmdBuf, dev.SCSIType); - sidecar.BlockMedia[0].SCSI.ModeSense10 = new DumpType(); - sidecar.BlockMedia[0].SCSI.ModeSense10.Image = options.OutputPrefix + ".modesense10.bin"; - sidecar.BlockMedia[0].SCSI.ModeSense10.Size = cmdBuf.Length; - sidecar.BlockMedia[0].SCSI.ModeSense10.Checksums = Core.Checksum.GetChecksums(cmdBuf).ToArray(); - writeToFile(sidecar.BlockMedia[0].SCSI.ModeSense10.Image, cmdBuf); - } - } - - sense = dev.ModeSense6(out cmdBuf, out senseBuf, false, ScsiModeSensePageControl.Current, 0x3F, 0x00, 5, out duration); - if(sense || dev.Error) - sense = dev.ModeSense6(out cmdBuf, out senseBuf, false, ScsiModeSensePageControl.Current, 0x3F, 0x00, 5, out duration); - if(sense || dev.Error) - sense = dev.ModeSense(out cmdBuf, out senseBuf, 5, out duration); - - if(!sense && !dev.Error) - { - if(Decoders.SCSI.Modes.DecodeMode6(cmdBuf, dev.SCSIType).HasValue) - { - decMode = Decoders.SCSI.Modes.DecodeMode6(cmdBuf, dev.SCSIType); - sidecar.BlockMedia[0].SCSI.ModeSense = new DumpType(); - sidecar.BlockMedia[0].SCSI.ModeSense.Image = options.OutputPrefix + ".modesense.bin"; - sidecar.BlockMedia[0].SCSI.ModeSense.Size = cmdBuf.Length; - sidecar.BlockMedia[0].SCSI.ModeSense.Checksums = Core.Checksum.GetChecksums(cmdBuf).ToArray(); - writeToFile(sidecar.BlockMedia[0].SCSI.ModeSense.Image, cmdBuf); - } - } - - if(decMode.HasValue) - { - scsiMediumType = (byte)decMode.Value.Header.MediumType; - if(decMode.Value.Header.BlockDescriptors != null && decMode.Value.Header.BlockDescriptors.Length >= 1) - scsiDensityCode = (byte)decMode.Value.Header.BlockDescriptors[0].Density; - - foreach(Decoders.SCSI.Modes.ModePage modePage in decMode.Value.Pages) - containsFloppyPage |= modePage.Page == 0x05; - } - } - } - } - - if(dskType == MediaType.Unknown) - dskType = MediaTypeFromSCSI.Get((byte)dev.SCSIType, dev.Manufacturer, dev.Model, scsiMediumType, scsiDensityCode, blocks, blockSize); - - if(dskType == MediaType.Unknown && dev.IsUSB && containsFloppyPage) - dskType = MediaType.FlashDrive; - - DicConsole.WriteLine("Media identified as {0}", dskType); - - byte[] readBuffer; - uint blocksToRead = 64; - - ulong errored = 0; - - aborted = false; - System.Console.CancelKeyPress += (sender, e) => - { - e.Cancel = aborted = true; - }; - - // TODO: Raw reading - bool read6 = false, read10 = false, read12 = false, read16 = false, readcd = false; - bool readLong10 = false, readLong16 = false, hldtstReadRaw = false, readLongDvd = false; - bool plextorReadRaw = false, syqReadLong6 = false, syqReadLong10 = false; - - #region CompactDisc dump - if(compactDisc) - { - if(toc == null) - { - DicConsole.ErrorWriteLine("Error trying to decode TOC..."); - return; - } - - if(options.Raw) - { - throw new NotImplementedException("Raw CD dumping not yet implemented"); - } - else - { - // TODO: Check subchannel capabilities - readcd = !dev.ReadCd(out readBuffer, out senseBuf, 0, 2448, 1, MmcSectorTypes.AllTypes, false, false, true, MmcHeaderCodes.AllHeaders, - true, true, MmcErrorField.None, MmcSubchannel.Raw, dev.Timeout, out duration); - - if(readcd) - DicConsole.WriteLine("Using MMC READ CD command."); - } - - DicConsole.WriteLine("Trying to read Lead-In..."); - bool gotLeadIn = false; - int leadInSectorsGood = 0, leadInSectorsTotal = 0; - - initDataFile(options.OutputPrefix + ".leadin.bin"); - dataChk = new Core.Checksum(); - - start = DateTime.UtcNow; - - readBuffer = null; - - for(int leadInBlock = -150; leadInBlock < 0; leadInBlock++) - { - if(aborted) - break; - - double cmdDuration = 0; - -#pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator - if(currentSpeed > maxSpeed && currentSpeed != 0) - maxSpeed = currentSpeed; - if(currentSpeed < minSpeed && currentSpeed != 0) - minSpeed = currentSpeed; -#pragma warning restore RECS0018 // Comparison of floating point numbers with equality operator - - DicConsole.Write("\rTrying to read lead-in sector {0} ({1:F3} MiB/sec.)", leadInBlock, currentSpeed); - - sense = dev.ReadCd(out readBuffer, out senseBuf, (uint)leadInBlock, 2448, 1, MmcSectorTypes.AllTypes, false, false, true, MmcHeaderCodes.AllHeaders, - true, true, MmcErrorField.None, MmcSubchannel.Raw, dev.Timeout, out cmdDuration); - - if(!sense && !dev.Error) - { - dataChk.Update(readBuffer); - writeToDataFile(readBuffer); - gotLeadIn = true; - leadInSectorsGood++; - leadInSectorsTotal++; - } - else - { - if(gotLeadIn) - { - // Write empty data - dataChk.Update(new byte[2448]); - writeToDataFile(new byte[2448]); - leadInSectorsTotal++; - } - } - -#pragma warning disable IDE0004 // Remove Unnecessary Cast - currentSpeed = ((double)2448 / (double)1048576) / (cmdDuration / (double)1000); -#pragma warning restore IDE0004 // Remove Unnecessary Cast - } - - closeDataFile(); - if(leadInSectorsGood > 0) - { - sidecar.OpticalDisc[0].LeadIn = new BorderType[1]; - sidecar.OpticalDisc[0].LeadIn[0] = new BorderType(); - sidecar.OpticalDisc[0].LeadIn[0].Image = options.OutputPrefix + ".leadin.bin"; - sidecar.OpticalDisc[0].LeadIn[0].Checksums = dataChk.End().ToArray(); - sidecar.OpticalDisc[0].LeadIn[0].Size = leadInSectorsTotal * 2448; - } - else - File.Delete(options.OutputPrefix + ".leadin.bin"); - - DicConsole.WriteLine(); - DicConsole.WriteLine("Got {0} lead-in sectors.", leadInSectorsGood); - - while(true) - { - if(readcd) - { - sense = dev.ReadCd(out readBuffer, out senseBuf, 0, 2448, blocksToRead, MmcSectorTypes.AllTypes, false, false, true, MmcHeaderCodes.AllHeaders, - true, true, MmcErrorField.None, MmcSubchannel.Raw, dev.Timeout, out duration); - if(dev.Error) - blocksToRead /= 2; - } - - if(!dev.Error || blocksToRead == 1) - break; - } - - if(dev.Error) - { - DicConsole.ErrorWriteLine("Device error {0} trying to guess ideal transfer length.", dev.LastError); - return; - } - - DicConsole.WriteLine("Reading {0} sectors at a time.", blocksToRead); - - initDataFile(options.OutputPrefix + ".bin"); - mhddLog = new MHDDLog(options.OutputPrefix + ".mhddlog.bin", dev, blocks, blockSize, blocksToRead); - ibgLog = new IBGLog(options.OutputPrefix + ".ibg", 0x0008); - - start = DateTime.UtcNow; - for(ulong i = 0; i < blocks; i += blocksToRead) - { - if(aborted) - break; - - double cmdDuration = 0; - - if((blocks - i) < blocksToRead) - blocksToRead = (uint)(blocks - i); - -#pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator - if(currentSpeed > maxSpeed && currentSpeed != 0) - maxSpeed = currentSpeed; - if(currentSpeed < minSpeed && currentSpeed != 0) - minSpeed = currentSpeed; -#pragma warning restore RECS0018 // Comparison of floating point numbers with equality operator - - DicConsole.Write("\rReading sector {0} of {1} ({2:F3} MiB/sec.)", i, blocks, currentSpeed); - - if(readcd) - { - sense = dev.ReadCd(out readBuffer, out senseBuf, (uint)i, 2448, blocksToRead, MmcSectorTypes.AllTypes, false, false, true, MmcHeaderCodes.AllHeaders, - true, true, MmcErrorField.None, MmcSubchannel.Raw, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - - if(!sense && !dev.Error) - { - mhddLog.Write(i, cmdDuration); - ibgLog.Write(i, currentSpeed * 1024); - writeToDataFile(readBuffer); - } - else - { - // TODO: Reset device after X errors - if(options.StopOnError) - return; // TODO: Return more cleanly - - // Write empty data - writeToDataFile(new byte[2448 * blocksToRead]); - - // TODO: Record error on mapfile - - errored += blocksToRead; - unreadableSectors.Add(i); - DicConsole.DebugWriteLine("Dump-Media", "READ error:\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); - if(cmdDuration < 500) - mhddLog.Write(i, 65535); - else - mhddLog.Write(i, cmdDuration); - - ibgLog.Write(i, 0); - } - -#pragma warning disable IDE0004 // Remove Unnecessary Cast - currentSpeed = ((double)2448 * blocksToRead / (double)1048576) / (cmdDuration / (double)1000); -#pragma warning restore IDE0004 // Remove Unnecessary Cast - } - DicConsole.WriteLine(); - end = DateTime.UtcNow; - mhddLog.Close(); -#pragma warning disable IDE0004 // Remove Unnecessary Cast - ibgLog.Close(dev, blocks, blockSize, (end - start).TotalSeconds, currentSpeed * 1024, (((double)blockSize * (double)(blocks + 1)) / 1024) / (totalDuration / 1000), options.DevicePath); -#pragma warning restore IDE0004 // Remove Unnecessary Cast - - #region Compact Disc Error handling - if(unreadableSectors.Count > 0 && !aborted) - { - List tmpList = new List(); - - foreach(ulong ur in unreadableSectors) - { - for(ulong i = ur; i < ur + blocksToRead; i++) - tmpList.Add(i); - } - - tmpList.Sort(); - - int pass = 0; - bool forward = true; - bool runningPersistent = false; - - unreadableSectors = tmpList; - - cdRepeatRetry: - ulong[] tmpArray = unreadableSectors.ToArray(); - foreach(ulong badSector in tmpArray) - { - if(aborted) - break; - - double cmdDuration = 0; - - DicConsole.Write("\rRetrying sector {0}, pass {1}, {3}{2}", badSector, pass + 1, forward ? "forward" : "reverse", runningPersistent ? "recovering partial data, " : ""); - - if(readcd) - { - sense = dev.ReadCd(out readBuffer, out senseBuf, (uint)badSector, 2448, blocksToRead, MmcSectorTypes.AllTypes, false, false, true, MmcHeaderCodes.AllHeaders, - true, true, MmcErrorField.None, MmcSubchannel.Raw, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - - if(!sense && !dev.Error) - { - unreadableSectors.Remove(badSector); - writeToDataFileAtPosition(readBuffer, badSector, blockSize); - } - else if(runningPersistent) - writeToDataFileAtPosition(readBuffer, badSector, blockSize); - } - - if(pass < options.RetryPasses && !aborted && unreadableSectors.Count > 0) - { - pass++; - forward = !forward; - unreadableSectors.Sort(); - unreadableSectors.Reverse(); - goto cdRepeatRetry; - } - - Decoders.SCSI.Modes.DecodedMode? currentMode = null; - Decoders.SCSI.Modes.ModePage? currentModePage = null; - byte[] md6 = null; - byte[] md10 = null; - - if(!runningPersistent && options.Persistent) - { - sense = dev.ModeSense6(out readBuffer, out senseBuf, false, ScsiModeSensePageControl.Current, 0x01, dev.Timeout, out duration); - if(sense) - { - sense = dev.ModeSense10(out readBuffer, out senseBuf, false, ScsiModeSensePageControl.Current, 0x01, dev.Timeout, out duration); - if(!sense) - currentMode = Decoders.SCSI.Modes.DecodeMode10(readBuffer, dev.SCSIType); - } - else - currentMode = Decoders.SCSI.Modes.DecodeMode6(readBuffer, dev.SCSIType); - - if(currentMode.HasValue) - currentModePage = currentMode.Value.Pages[0]; - - Decoders.SCSI.Modes.ModePage_01_MMC pgMMC = new Decoders.SCSI.Modes.ModePage_01_MMC(); - pgMMC.PS = false; - pgMMC.ReadRetryCount = 255; - pgMMC.Parameter = 0x20; - - Decoders.SCSI.Modes.DecodedMode md = new Decoders.SCSI.Modes.DecodedMode(); - md.Header = new Decoders.SCSI.Modes.ModeHeader(); - md.Pages = new Decoders.SCSI.Modes.ModePage[1]; - md.Pages[0] = new Decoders.SCSI.Modes.ModePage(); - md.Pages[0].Page = 0x01; - md.Pages[0].Subpage = 0x00; - md.Pages[0].PageResponse = Decoders.SCSI.Modes.EncodeModePage_01_MMC(pgMMC); - md6 = Decoders.SCSI.Modes.EncodeMode6(md, dev.SCSIType); - md10 = Decoders.SCSI.Modes.EncodeMode10(md, dev.SCSIType); - - sense = dev.ModeSelect(md6, out senseBuf, true, false, dev.Timeout, out duration); - if(sense) - { - sense = dev.ModeSelect10(md10, out senseBuf, true, false, dev.Timeout, out duration); - } - - runningPersistent = true; - if(!sense && !dev.Error) - { - pass--; - goto cdRepeatRetry; - } - } - else if(runningPersistent && options.Persistent && currentModePage.HasValue) - { - Decoders.SCSI.Modes.DecodedMode md = new Decoders.SCSI.Modes.DecodedMode(); - md.Header = new Decoders.SCSI.Modes.ModeHeader(); - md.Pages = new Decoders.SCSI.Modes.ModePage[1]; - md.Pages[0] = currentModePage.Value; - md6 = Decoders.SCSI.Modes.EncodeMode6(md, dev.SCSIType); - md10 = Decoders.SCSI.Modes.EncodeMode10(md, dev.SCSIType); - - sense = dev.ModeSelect(md6, out senseBuf, true, false, dev.Timeout, out duration); - if(sense) - { - sense = dev.ModeSelect10(md10, out senseBuf, true, false, dev.Timeout, out duration); - } - } - - DicConsole.WriteLine(); - } - #endregion Compact Disc Error handling - - dataChk = new Core.Checksum(); - dataFs.Seek(0, SeekOrigin.Begin); - blocksToRead = 500; - - for(ulong i = 0; i < blocks; i += blocksToRead) - { - if(aborted) - break; - - if((blocks - i) < blocksToRead) - blocksToRead = (uint)(blocks - i); - - DicConsole.Write("\rChecksumming sector {0} of {1} ({2:F3} MiB/sec.)", i, blocks, currentSpeed); - - DateTime chkStart = DateTime.UtcNow; - byte[] dataToCheck = new byte[blockSize * blocksToRead]; - dataFs.Read(dataToCheck, 0, (int)(blockSize * blocksToRead)); - dataChk.Update(dataToCheck); - DateTime chkEnd = DateTime.UtcNow; - - double chkDuration = (chkEnd - chkStart).TotalMilliseconds; - totalChkDuration += chkDuration; - -#pragma warning disable IDE0004 // Remove Unnecessary Cast - currentSpeed = ((double)blockSize * blocksToRead / (double)1048576) / (chkDuration / (double)1000); -#pragma warning restore IDE0004 // Remove Unnecessary Cast - } - DicConsole.WriteLine(); - closeDataFile(); - end = DateTime.UtcNow; - - // TODO: Correct this - sidecar.OpticalDisc[0].Checksums = dataChk.End().ToArray(); - sidecar.OpticalDisc[0].DumpHardwareArray = new DumpHardwareType[1]; - sidecar.OpticalDisc[0].DumpHardwareArray[0] = new DumpHardwareType(); - sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents = new ExtentType[1]; - sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents[0] = new ExtentType(); - sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents[0].Start = 0; - sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents[0].End = (int)(blocks - 1); - sidecar.OpticalDisc[0].DumpHardwareArray[0].Manufacturer = dev.Manufacturer; - sidecar.OpticalDisc[0].DumpHardwareArray[0].Model = dev.Model; - sidecar.OpticalDisc[0].DumpHardwareArray[0].Revision = dev.Revision; - sidecar.OpticalDisc[0].DumpHardwareArray[0].Software = new SoftwareType(); - sidecar.OpticalDisc[0].DumpHardwareArray[0].Software.Name = "DiscImageChef"; - sidecar.OpticalDisc[0].DumpHardwareArray[0].Software.OperatingSystem = dev.PlatformID.ToString(); - sidecar.OpticalDisc[0].DumpHardwareArray[0].Software.Version = typeof(MainClass).Assembly.GetName().Version.ToString(); - sidecar.OpticalDisc[0].Image = new ImageType(); - sidecar.OpticalDisc[0].Image.format = "Raw disk image (sector by sector copy)"; - sidecar.OpticalDisc[0].Image.Value = options.OutputPrefix + ".bin"; - sidecar.OpticalDisc[0].Sessions = 1; - sidecar.OpticalDisc[0].Tracks = new[] { 1 }; - sidecar.OpticalDisc[0].Track = new Schemas.TrackType[1]; - sidecar.OpticalDisc[0].Track[0] = new Schemas.TrackType(); - sidecar.OpticalDisc[0].Track[0].BytesPerSector = (int)blockSize; - sidecar.OpticalDisc[0].Track[0].Checksums = sidecar.OpticalDisc[0].Checksums; - sidecar.OpticalDisc[0].Track[0].EndSector = (long)(blocks - 1); - sidecar.OpticalDisc[0].Track[0].Image = new ImageType(); - sidecar.OpticalDisc[0].Track[0].Image.format = "BINARY"; - sidecar.OpticalDisc[0].Track[0].Image.offset = 0; - sidecar.OpticalDisc[0].Track[0].Image.offsetSpecified = true; - sidecar.OpticalDisc[0].Track[0].Image.Value = sidecar.OpticalDisc[0].Image.Value; - sidecar.OpticalDisc[0].Track[0].Sequence = new TrackSequenceType(); - sidecar.OpticalDisc[0].Track[0].Sequence.Session = 1; - sidecar.OpticalDisc[0].Track[0].Sequence.TrackNumber = 1; - sidecar.OpticalDisc[0].Track[0].Size = (long)(blocks * blockSize); - sidecar.OpticalDisc[0].Track[0].StartSector = 0; - sidecar.OpticalDisc[0].Track[0].TrackType1 = TrackTypeTrackType.mode1; - sidecar.OpticalDisc[0].Dimensions = Metadata.Dimensions.DimensionsFromMediaType(dskType); - string xmlDskTyp, xmlDskSubTyp; - Metadata.MediaType.MediaTypeToString(dskType, out xmlDskTyp, out xmlDskSubTyp); - sidecar.OpticalDisc[0].DiscType = xmlDskTyp; - sidecar.OpticalDisc[0].DiscSubType = xmlDskSubTyp; - } - #endregion CompactDisc dump - #region Xbox Game Disc - else if(isXbox) - { - byte[] ssBuf; - sense = dev.KreonExtractSS(out ssBuf, out senseBuf, dev.Timeout, out duration); - if(sense) - { - DicConsole.ErrorWriteLine("Cannot get Xbox Security Sector, not continuing."); - return; - } - - Decoders.Xbox.SS.SecuritySector? xboxSS = Decoders.Xbox.SS.Decode(ssBuf); - if(!xboxSS.HasValue) - { - DicConsole.ErrorWriteLine("Cannot decode Xbox Security Sector, not continuing."); - return; - } - - - // TODO: Correct metadata - /*sidecar.OpticalDisc[0].XboxSecuritySectors = new DumpType(); - sidecar.OpticalDisc[0].XboxSecuritySectors.Image = options.OutputPrefix + ".bca.bin"; - sidecar.OpticalDisc[0].XboxSecuritySectors.Size = cmdBuf.Length; - sidecar.OpticalDisc[0].XboxSecuritySectors.Checksums = Core.Checksum.GetChecksums(cmbBuf).ToArray(); - writeToFile(sidecar.OpticalDisc[0].XboxSecuritySectors.Image, tmpBuf);*/ - writeToFile(options.OutputPrefix + ".ss.bin", cmdBuf); - - ulong l0Video, l1Video, middleZone, gameSize, totalSize, layerBreak; - - // Get video partition size - DicConsole.DebugWriteLine("Dump-media command", "Getting video partition size"); - sense = dev.KreonLock(out senseBuf, dev.Timeout, out duration); - if(sense) - { - DicConsole.ErrorWriteLine("Cannot lock drive, not continuing."); - return; - } - sense = dev.ReadCapacity(out readBuffer, out senseBuf, dev.Timeout, out duration); - if(sense) - { - DicConsole.ErrorWriteLine("Cannot get disc capacity."); - return; - } - totalSize = (ulong)((readBuffer[0] << 24) + (readBuffer[1] << 16) + (readBuffer[2] << 8) + (readBuffer[3])); - sense = dev.ReadDiscStructure(out readBuffer, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.PhysicalInformation, 0, 0, out duration); - if(sense) - { - DicConsole.ErrorWriteLine("Cannot get PFI."); - return; - } - DicConsole.DebugWriteLine("Dump-media command", "Video partition total size: {0} sectors", totalSize); - l0Video = Decoders.DVD.PFI.Decode(readBuffer).Value.Layer0EndPSN - Decoders.DVD.PFI.Decode(readBuffer).Value.DataAreaStartPSN + 1; - l1Video = totalSize - l0Video + 1; - - // Get game partition size - DicConsole.DebugWriteLine("Dump-media command", "Getting game partition size"); - sense = dev.KreonUnlockXtreme(out senseBuf, dev.Timeout, out duration); - if(sense) - { - DicConsole.ErrorWriteLine("Cannot unlock drive, not continuing."); - return; - } - sense = dev.ReadCapacity(out readBuffer, out senseBuf, dev.Timeout, out duration); - if(sense) - { - DicConsole.ErrorWriteLine("Cannot get disc capacity."); - return; - } - gameSize = (ulong)((readBuffer[0] << 24) + (readBuffer[1] << 16) + (readBuffer[2] << 8) + (readBuffer[3])) + 1; - DicConsole.DebugWriteLine("Dump-media command", "Game partition total size: {0} sectors", gameSize); - - // Get middle zone size - DicConsole.DebugWriteLine("Dump-media command", "Getting middle zone size"); - sense = dev.KreonUnlockWxripper(out senseBuf, dev.Timeout, out duration); - if(sense) - { - DicConsole.ErrorWriteLine("Cannot unlock drive, not continuing."); - return; - } - sense = dev.ReadCapacity(out readBuffer, out senseBuf, dev.Timeout, out duration); - if(sense) - { - DicConsole.ErrorWriteLine("Cannot get disc capacity."); - return; - } - totalSize = (ulong)((readBuffer[0] << 24) + (readBuffer[1] << 16) + (readBuffer[2] << 8) + (readBuffer[3])); - sense = dev.ReadDiscStructure(out readBuffer, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.PhysicalInformation, 0, 0, out duration); - if(sense) - { - DicConsole.ErrorWriteLine("Cannot get PFI."); - return; - } - DicConsole.DebugWriteLine("Dump-media command", "Unlocked total size: {0} sectors", totalSize); - middleZone = totalSize - (Decoders.DVD.PFI.Decode(readBuffer).Value.Layer0EndPSN - Decoders.DVD.PFI.Decode(readBuffer).Value.DataAreaStartPSN + 1) - gameSize + 1; - - totalSize = l0Video + l1Video + middleZone * 2 + gameSize; - layerBreak = l0Video + middleZone + gameSize / 2; - - DicConsole.WriteLine("Video layer 0 size: {0} sectors", l0Video); - DicConsole.WriteLine("Video layer 1 size: {0} sectors", l1Video); - DicConsole.WriteLine("Middle zone size: {0} sectors", middleZone); - DicConsole.WriteLine("Game data size: {0} sectors", gameSize); - DicConsole.WriteLine("Total size: {0} sectors", totalSize); - DicConsole.WriteLine("Real layer break: {0}", layerBreak); - DicConsole.WriteLine(); - - read12 = !dev.Read12(out readBuffer, out senseBuf, 0, false, true, false, false, 0, blockSize, 0, 1, false, dev.Timeout, out duration); - if(!read12) - { - DicConsole.ErrorWriteLine("Cannot read medium, aborting scan..."); - return; - } - - DicConsole.WriteLine("Using SCSI READ (12) command."); - - while(true) - { - if(read12) - { - sense = dev.Read12(out readBuffer, out senseBuf, 0, false, false, false, false, 0, blockSize, 0, blocksToRead, false, dev.Timeout, out duration); - if(dev.Error) - blocksToRead /= 2; - } - - if(!dev.Error || blocksToRead == 1) - break; - } - - if(dev.Error) - { - DicConsole.ErrorWriteLine("Device error {0} trying to guess ideal transfer length.", dev.LastError); - return; - } - - - DicConsole.WriteLine("Reading {0} sectors at a time.", blocksToRead); - - mhddLog = new MHDDLog(options.OutputPrefix + ".mhddlog.bin", dev, blocks, blockSize, blocksToRead); - ibgLog = new IBGLog(options.OutputPrefix + ".ibg", currentProfile); - initDataFile(options.OutputPrefix + ".bin"); - - start = DateTime.UtcNow; - - readBuffer = null; - - ulong currentSector = 0; - double cmdDuration = 0; - uint saveBlocksToRead = blocksToRead; - - for(int e = 0; e <= 16; e++) - { - ulong extentStart, extentEnd; - // Extents - if(e < 16) - { - if(xboxSS.Value.Extents[e].StartPSN <= xboxSS.Value.Layer0EndPSN) - extentStart = xboxSS.Value.Extents[e].StartPSN - 0x30000; - else - extentStart = (xboxSS.Value.Layer0EndPSN + 1) * 2 - ((xboxSS.Value.Extents[e].StartPSN ^ 0xFFFFFF) + 1) - 0x30000; - if(xboxSS.Value.Extents[e].EndPSN <= xboxSS.Value.Layer0EndPSN) - extentEnd = xboxSS.Value.Extents[e].EndPSN - 0x30000; - else - extentEnd = (xboxSS.Value.Layer0EndPSN + 1) * 2 - ((xboxSS.Value.Extents[e].EndPSN ^ 0xFFFFFF) + 1) - 0x30000; - } - // After last extent - else - { - extentStart = blocks; - extentEnd = blocks; - } - - for(ulong i = currentSector; i < extentStart; i += blocksToRead) - { - saveBlocksToRead = blocksToRead; - if(aborted) - break; - - if((extentStart - i) < blocksToRead) - blocksToRead = (uint)(extentStart - i); - -#pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator - if(currentSpeed > maxSpeed && currentSpeed != 0) - maxSpeed = currentSpeed; - if(currentSpeed < minSpeed && currentSpeed != 0) - minSpeed = currentSpeed; -#pragma warning restore RECS0018 // Comparison of floating point numbers with equality operator - - DicConsole.Write("\rReading sector {0} of {1} ({2:F3} MiB/sec.)", i, totalSize, currentSpeed); - - sense = dev.Read12(out readBuffer, out senseBuf, 0, false, false, false, false, (uint)i, blockSize, 0, blocksToRead, false, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - - if(!sense && !dev.Error) - { - mhddLog.Write(i, cmdDuration); - ibgLog.Write(i, currentSpeed * 1024); - writeToDataFile(readBuffer); - } - else - { - // TODO: Reset device after X errors - if(options.StopOnError) - return; // TODO: Return more cleanly - - // Write empty data - writeToDataFile(new byte[blockSize * blocksToRead]); - - // TODO: Record error on mapfile - - errored += blocksToRead; - unreadableSectors.Add(i); - DicConsole.DebugWriteLine("Dump-Media", "READ error:\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); - if(cmdDuration < 500) - mhddLog.Write(i, 65535); - else - mhddLog.Write(i, cmdDuration); - - ibgLog.Write(i, 0); - } - -#pragma warning disable IDE0004 // Remove Unnecessary Cast - currentSpeed = ((double)blockSize * blocksToRead / (double)1048576) / (cmdDuration / (double)1000); -#pragma warning restore IDE0004 // Remove Unnecessary Cast - blocksToRead = saveBlocksToRead; - } - - for(ulong i = extentStart; i <= extentEnd; i += blocksToRead) - { - saveBlocksToRead = blocksToRead; - if(aborted) - break; - - if((extentEnd - i) < blocksToRead) - blocksToRead = (uint)(extentEnd - i) + 1; - - mhddLog.Write(i, cmdDuration); - ibgLog.Write(i, currentSpeed * 1024); - writeToDataFile(new byte[blocksToRead * 2048]); - blocksToRead = saveBlocksToRead; - } - - currentSector = extentEnd + 1; - if(currentSector >= blocks) - break; - } - - // Middle Zone D - for(ulong middle = 0; middle < (middleZone - 1); middle += blocksToRead) - { - if(aborted) - break; - - if(((middleZone - 1) - middle) < blocksToRead) - blocksToRead = (uint)((middleZone - 1) - middle); - - DicConsole.Write("\rReading sector {0} of {1} ({2:F3} MiB/sec.)", middle + currentSector, totalSize, currentSpeed); - - mhddLog.Write(middle + currentSector, cmdDuration); - ibgLog.Write(middle + currentSector, currentSpeed * 1024); - writeToDataFile(new byte[blockSize * blocksToRead]); - - currentSector += blocksToRead; - } - - blocksToRead = saveBlocksToRead; - - sense = dev.KreonLock(out senseBuf, dev.Timeout, out duration); - if(sense) - { - DicConsole.ErrorWriteLine("Cannot lock drive, not continuing."); - return; - } - sense = dev.ReadCapacity(out readBuffer, out senseBuf, dev.Timeout, out duration); - if(sense) - { - DicConsole.ErrorWriteLine("Cannot get disc capacity."); - return; - } - - // Video Layer 1 - for(ulong l1 = l0Video; l1 < (l0Video + l1Video); l1 += blocksToRead) - { - if(aborted) - break; - - if(((l0Video + l1Video) - l1) < blocksToRead) - blocksToRead = (uint)((l0Video + l1Video) - l1); - -#pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator - if(currentSpeed > maxSpeed && currentSpeed != 0) - maxSpeed = currentSpeed; - if(currentSpeed < minSpeed && currentSpeed != 0) - minSpeed = currentSpeed; -#pragma warning restore RECS0018 // Comparison of floating point numbers with equality operator - - DicConsole.Write("\rReading sector {0} of {1} ({2:F3} MiB/sec.)", currentSector, totalSize, currentSpeed); - - sense = dev.Read12(out readBuffer, out senseBuf, 0, false, false, false, false, (uint)l1, blockSize, 0, blocksToRead, false, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - - if(!sense && !dev.Error) - { - mhddLog.Write(currentSector, cmdDuration); - ibgLog.Write(currentSector, currentSpeed * 1024); - writeToDataFile(readBuffer); - } - else - { - // TODO: Reset device after X errors - if(options.StopOnError) - return; // TODO: Return more cleanly - - // Write empty data - writeToDataFile(new byte[blockSize * blocksToRead]); - - // TODO: Record error on mapfile - - // TODO: Handle errors in video partition - //errored += blocksToRead; - //unreadableSectors.Add(l1); - DicConsole.DebugWriteLine("Dump-Media", "READ error:\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); - if(cmdDuration < 500) - mhddLog.Write(l1, 65535); - else - mhddLog.Write(l1, cmdDuration); - - ibgLog.Write(l1, 0); - } - -#pragma warning disable IDE0004 // Remove Unnecessary Cast - currentSpeed = ((double)blockSize * blocksToRead / (double)1048576) / (cmdDuration / (double)1000); -#pragma warning restore IDE0004 // Remove Unnecessary Cast - currentSector += blocksToRead; - } - - sense = dev.KreonUnlockWxripper(out senseBuf, dev.Timeout, out duration); - if(sense) - { - DicConsole.ErrorWriteLine("Cannot unlock drive, not continuing."); - return; - } - sense = dev.ReadCapacity(out readBuffer, out senseBuf, dev.Timeout, out duration); - if(sense) - { - DicConsole.ErrorWriteLine("Cannot get disc capacity."); - return; - } - - end = DateTime.UtcNow; - DicConsole.WriteLine(); - mhddLog.Close(); -#pragma warning disable IDE0004 // Remove Unnecessary Cast - ibgLog.Close(dev, blocks, blockSize, (end - start).TotalSeconds, currentSpeed * 1024, (((double)blockSize * (double)(blocks + 1)) / 1024) / (totalDuration / 1000), options.DevicePath); -#pragma warning restore IDE0004 // Remove Unnecessary Cast - - #region Error handling - if(unreadableSectors.Count > 0 && !aborted) - { - List tmpList = new List(); - - foreach(ulong ur in unreadableSectors) - { - for(ulong i = ur; i < ur + blocksToRead; i++) - tmpList.Add(i); - } - - tmpList.Sort(); - - int pass = 0; - bool forward = true; - bool runningPersistent = false; - - unreadableSectors = tmpList; - - repeatRetry: - ulong[] tmpArray = unreadableSectors.ToArray(); - foreach(ulong badSector in tmpArray) - { - if(aborted) - break; - - cmdDuration = 0; - - DicConsole.Write("\rRetrying sector {0}, pass {1}, {3}{2}", badSector, pass + 1, forward ? "forward" : "reverse", runningPersistent ? "recovering partial data, " : ""); - - sense = dev.Read12(out readBuffer, out senseBuf, 0, false, false, false, false, (uint)badSector, blockSize, 0, 1, false, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - - if(!sense && !dev.Error) - { - unreadableSectors.Remove(badSector); - writeToDataFileAtPosition(readBuffer, badSector, blockSize); - } - else if(runningPersistent) - writeToDataFileAtPosition(readBuffer, badSector, blockSize); - } - - if(pass < options.RetryPasses && !aborted && unreadableSectors.Count > 0) - { - pass++; - forward = !forward; - unreadableSectors.Sort(); - unreadableSectors.Reverse(); - goto repeatRetry; - } - - Decoders.SCSI.Modes.DecodedMode? currentMode = null; - Decoders.SCSI.Modes.ModePage? currentModePage = null; - byte[] md6 = null; - byte[] md10 = null; - - if(!runningPersistent && options.Persistent) - { - sense = dev.ModeSense6(out readBuffer, out senseBuf, false, ScsiModeSensePageControl.Current, 0x01, dev.Timeout, out duration); - if(sense) - { - sense = dev.ModeSense10(out readBuffer, out senseBuf, false, ScsiModeSensePageControl.Current, 0x01, dev.Timeout, out duration); - if(!sense) - currentMode = Decoders.SCSI.Modes.DecodeMode10(readBuffer, dev.SCSIType); - } - else - currentMode = Decoders.SCSI.Modes.DecodeMode6(readBuffer, dev.SCSIType); - - if(currentMode.HasValue) - currentModePage = currentMode.Value.Pages[0]; - - if(dev.SCSIType == Decoders.SCSI.PeripheralDeviceTypes.MultiMediaDevice) - { - Decoders.SCSI.Modes.ModePage_01_MMC pgMMC = new Decoders.SCSI.Modes.ModePage_01_MMC(); - pgMMC.PS = false; - pgMMC.ReadRetryCount = 255; - pgMMC.Parameter = 0x20; - - Decoders.SCSI.Modes.DecodedMode md = new Decoders.SCSI.Modes.DecodedMode(); - md.Header = new Decoders.SCSI.Modes.ModeHeader(); - md.Pages = new Decoders.SCSI.Modes.ModePage[1]; - md.Pages[0] = new Decoders.SCSI.Modes.ModePage(); - md.Pages[0].Page = 0x01; - md.Pages[0].Subpage = 0x00; - md.Pages[0].PageResponse = Decoders.SCSI.Modes.EncodeModePage_01_MMC(pgMMC); - md6 = Decoders.SCSI.Modes.EncodeMode6(md, dev.SCSIType); - md10 = Decoders.SCSI.Modes.EncodeMode10(md, dev.SCSIType); - } - else - { - Decoders.SCSI.Modes.ModePage_01 pg = new Decoders.SCSI.Modes.ModePage_01(); - pg.PS = false; - pg.AWRE = false; - pg.ARRE = false; - pg.TB = true; - pg.RC = false; - pg.EER = true; - pg.PER = false; - pg.DTE = false; - pg.DCR = false; - pg.ReadRetryCount = 255; - - Decoders.SCSI.Modes.DecodedMode md = new Decoders.SCSI.Modes.DecodedMode(); - md.Header = new Decoders.SCSI.Modes.ModeHeader(); - md.Pages = new Decoders.SCSI.Modes.ModePage[1]; - md.Pages[0] = new Decoders.SCSI.Modes.ModePage(); - md.Pages[0].Page = 0x01; - md.Pages[0].Subpage = 0x00; - md.Pages[0].PageResponse = Decoders.SCSI.Modes.EncodeModePage_01(pg); - md6 = Decoders.SCSI.Modes.EncodeMode6(md, dev.SCSIType); - md10 = Decoders.SCSI.Modes.EncodeMode10(md, dev.SCSIType); - } - - sense = dev.ModeSelect(md6, out senseBuf, true, false, dev.Timeout, out duration); - if(sense) - { - sense = dev.ModeSelect10(md10, out senseBuf, true, false, dev.Timeout, out duration); - } - - runningPersistent = true; - if(!sense && !dev.Error) - { - pass--; - goto repeatRetry; - } - } - else if(runningPersistent && options.Persistent && currentModePage.HasValue) - { - Decoders.SCSI.Modes.DecodedMode md = new Decoders.SCSI.Modes.DecodedMode(); - md.Header = new Decoders.SCSI.Modes.ModeHeader(); - md.Pages = new Decoders.SCSI.Modes.ModePage[1]; - md.Pages[0] = currentModePage.Value; - md6 = Decoders.SCSI.Modes.EncodeMode6(md, dev.SCSIType); - md10 = Decoders.SCSI.Modes.EncodeMode10(md, dev.SCSIType); - - sense = dev.ModeSelect(md6, out senseBuf, true, false, dev.Timeout, out duration); - if(sense) - { - sense = dev.ModeSelect10(md10, out senseBuf, true, false, dev.Timeout, out duration); - } - } - - DicConsole.WriteLine(); - } - #endregion Error handling - - dataChk = new Core.Checksum(); - dataFs.Seek(0, SeekOrigin.Begin); - blocksToRead = 500; - - blocks = totalSize; - - for(ulong i = 0; i < blocks; i += blocksToRead) - { - if(aborted) - break; - - if((blocks - i) < blocksToRead) - blocksToRead = (uint)(blocks - i); - - DicConsole.Write("\rChecksumming sector {0} of {1} ({2:F3} MiB/sec.)", i, blocks, currentSpeed); - - DateTime chkStart = DateTime.UtcNow; - byte[] dataToCheck = new byte[blockSize * blocksToRead]; - dataFs.Read(dataToCheck, 0, (int)(blockSize * blocksToRead)); - dataChk.Update(dataToCheck); - DateTime chkEnd = DateTime.UtcNow; - - double chkDuration = (chkEnd - chkStart).TotalMilliseconds; - totalChkDuration += chkDuration; - -#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created - currentSpeed = ((double)blockSize * blocksToRead / (double)1048576) / (chkDuration / (double)1000); -#pragma warning restore IDE0004 // Cast is necessary, otherwise incorrect value is created - } - DicConsole.WriteLine(); - closeDataFile(); - end = DateTime.UtcNow; - - PluginBase plugins = new PluginBase(); - plugins.RegisterAllPlugins(); - ImagePlugin _imageFormat; - FiltersList filtersList = new FiltersList(); - Filter inputFilter = filtersList.GetFilter(options.OutputPrefix + ".bin"); - - if(inputFilter == null) - { - DicConsole.ErrorWriteLine("Cannot open file just created, this should not happen."); - return; - } - - _imageFormat = ImageFormat.Detect(inputFilter); - PartitionType[] xmlFileSysInfo = null; - - try - { - if(!_imageFormat.OpenImage(inputFilter)) - _imageFormat = null; - } - catch - { - _imageFormat = null; - } - - if(_imageFormat != null) - { - List partitions = new List(); - - foreach(PartPlugin _partplugin in plugins.PartPluginsList.Values) - { - List _partitions; - - if(_partplugin.GetInformation(_imageFormat, out _partitions)) - { - partitions.AddRange(_partitions); - Core.Statistics.AddPartition(_partplugin.Name); - } - } - - if(partitions.Count > 0) - { - xmlFileSysInfo = new PartitionType[partitions.Count]; - for(int i = 0; i < partitions.Count; i++) - { - xmlFileSysInfo[i] = new PartitionType(); - xmlFileSysInfo[i].Description = partitions[i].PartitionDescription; - xmlFileSysInfo[i].EndSector = (int)(partitions[i].PartitionStartSector + partitions[i].PartitionSectors - 1); - xmlFileSysInfo[i].Name = partitions[i].PartitionName; - xmlFileSysInfo[i].Sequence = (int)partitions[i].PartitionSequence; - xmlFileSysInfo[i].StartSector = (int)partitions[i].PartitionStartSector; - xmlFileSysInfo[i].Type = partitions[i].PartitionType; - - List lstFs = new List(); - - foreach(Filesystem _plugin in plugins.PluginsList.Values) - { - try - { - if(_plugin.Identify(_imageFormat, partitions[i].PartitionStartSector, partitions[i].PartitionStartSector + partitions[i].PartitionSectors - 1)) - { - string foo; - _plugin.GetInformation(_imageFormat, partitions[i].PartitionStartSector, partitions[i].PartitionStartSector + partitions[i].PartitionSectors - 1, out foo); - lstFs.Add(_plugin.XmlFSType); - Core.Statistics.AddFilesystem(_plugin.XmlFSType.Type); - - if(_plugin.XmlFSType.Type == "Opera") - dskType = MediaType.ThreeDO; - if(_plugin.XmlFSType.Type == "PC Engine filesystem") - dskType = MediaType.SuperCDROM2; - if(_plugin.XmlFSType.Type == "Nintendo Wii filesystem") - dskType = MediaType.WOD; - if(_plugin.XmlFSType.Type == "Nintendo Gamecube filesystem") - dskType = MediaType.GOD; - } - } -#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body - catch -#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body - { - //DicConsole.DebugWriteLine("Dump-media command", "Plugin {0} crashed", _plugin.Name); - } - } - - if(lstFs.Count > 0) - xmlFileSysInfo[i].FileSystems = lstFs.ToArray(); - } - } - else - { - xmlFileSysInfo = new PartitionType[1]; - xmlFileSysInfo[0] = new PartitionType(); - xmlFileSysInfo[0].EndSector = (int)(blocks - 1); - xmlFileSysInfo[0].StartSector = 0; - - List lstFs = new List(); - - foreach(Filesystem _plugin in plugins.PluginsList.Values) - { - try - { - if(_plugin.Identify(_imageFormat, (blocks - 1), 0)) - { - string foo; - _plugin.GetInformation(_imageFormat, (blocks - 1), 0, out foo); - lstFs.Add(_plugin.XmlFSType); - Core.Statistics.AddFilesystem(_plugin.XmlFSType.Type); - - if(_plugin.XmlFSType.Type == "Opera") - dskType = MediaType.ThreeDO; - if(_plugin.XmlFSType.Type == "PC Engine filesystem") - dskType = MediaType.SuperCDROM2; - if(_plugin.XmlFSType.Type == "Nintendo Wii filesystem") - dskType = MediaType.WOD; - if(_plugin.XmlFSType.Type == "Nintendo Gamecube filesystem") - dskType = MediaType.GOD; - } - } -#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body - catch -#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body - { - //DicConsole.DebugWriteLine("Create-sidecar command", "Plugin {0} crashed", _plugin.Name); - } - } - - if(lstFs.Count > 0) - xmlFileSysInfo[0].FileSystems = lstFs.ToArray(); - } - } - - sidecar.OpticalDisc[0].Checksums = dataChk.End().ToArray(); - sidecar.OpticalDisc[0].DumpHardwareArray = new DumpHardwareType[1]; - sidecar.OpticalDisc[0].DumpHardwareArray[0] = new DumpHardwareType(); - sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents = new ExtentType[1]; - sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents[0] = new ExtentType(); - sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents[0].Start = 0; - sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents[0].End = (int)(blocks - 1); - sidecar.OpticalDisc[0].DumpHardwareArray[0].Manufacturer = dev.Manufacturer; - sidecar.OpticalDisc[0].DumpHardwareArray[0].Model = dev.Model; - sidecar.OpticalDisc[0].DumpHardwareArray[0].Revision = dev.Revision; - sidecar.OpticalDisc[0].DumpHardwareArray[0].Software = new SoftwareType(); - sidecar.OpticalDisc[0].DumpHardwareArray[0].Software.Name = "DiscImageChef"; - sidecar.OpticalDisc[0].DumpHardwareArray[0].Software.OperatingSystem = dev.PlatformID.ToString(); - sidecar.OpticalDisc[0].DumpHardwareArray[0].Software.Version = typeof(MainClass).Assembly.GetName().Version.ToString(); - sidecar.OpticalDisc[0].Image = new ImageType(); - sidecar.OpticalDisc[0].Image.format = "Raw disk image (sector by sector copy)"; - sidecar.OpticalDisc[0].Image.Value = options.OutputPrefix + ".bin"; - sidecar.OpticalDisc[0].Layers = new LayersType(); - sidecar.OpticalDisc[0].Layers.type = LayersTypeType.OTP; - sidecar.OpticalDisc[0].Layers.typeSpecified = true; - sidecar.OpticalDisc[0].Layers.Sectors = new SectorsType[1]; - sidecar.OpticalDisc[0].Layers.Sectors[0] = new SectorsType(); - sidecar.OpticalDisc[0].Layers.Sectors[0].Value = (long)layerBreak; - sidecar.OpticalDisc[0].Sessions = 1; - sidecar.OpticalDisc[0].Tracks = new[] { 1 }; - sidecar.OpticalDisc[0].Track = new Schemas.TrackType[1]; - sidecar.OpticalDisc[0].Track[0] = new Schemas.TrackType(); - sidecar.OpticalDisc[0].Track[0].BytesPerSector = (int)blockSize; - sidecar.OpticalDisc[0].Track[0].Checksums = sidecar.OpticalDisc[0].Checksums; - sidecar.OpticalDisc[0].Track[0].EndSector = (long)(blocks - 1); - sidecar.OpticalDisc[0].Track[0].Image = new ImageType(); - sidecar.OpticalDisc[0].Track[0].Image.format = "BINARY"; - sidecar.OpticalDisc[0].Track[0].Image.offset = 0; - sidecar.OpticalDisc[0].Track[0].Image.offsetSpecified = true; - sidecar.OpticalDisc[0].Track[0].Image.Value = sidecar.OpticalDisc[0].Image.Value; - sidecar.OpticalDisc[0].Track[0].Sequence = new TrackSequenceType(); - sidecar.OpticalDisc[0].Track[0].Sequence.Session = 1; - sidecar.OpticalDisc[0].Track[0].Sequence.TrackNumber = 1; - sidecar.OpticalDisc[0].Track[0].Size = (long)(totalSize * blockSize); - sidecar.OpticalDisc[0].Track[0].StartSector = 0; - if(xmlFileSysInfo != null) - sidecar.OpticalDisc[0].Track[0].FileSystemInformation = xmlFileSysInfo; - sidecar.OpticalDisc[0].Track[0].TrackType1 = TrackTypeTrackType.dvd; - sidecar.OpticalDisc[0].Dimensions = Metadata.Dimensions.DimensionsFromMediaType(dskType); - string xmlDskTyp, xmlDskSubTyp; - Metadata.MediaType.MediaTypeToString(dskType, out xmlDskTyp, out xmlDskSubTyp); - sidecar.OpticalDisc[0].DiscType = xmlDskTyp; - sidecar.OpticalDisc[0].DiscSubType = xmlDskSubTyp; - } - #endregion Xbox Game Disc - else - { - uint longBlockSize = blockSize; - bool rawAble = false; - - if(options.Raw) - { - bool testSense; - Decoders.SCSI.FixedSense? decSense; - - if(dev.SCSIType != Decoders.SCSI.PeripheralDeviceTypes.MultiMediaDevice) - { - /*testSense = dev.ReadLong16(out readBuffer, out senseBuf, false, 0, 0xFFFF, dev.Timeout, out duration); - if (testSense && !dev.Error) - { - decSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf); - if (decSense.HasValue) - { - if (decSense.Value.SenseKey == DiscImageChef.Decoders.SCSI.SenseKeys.IllegalRequest && - decSense.Value.ASC == 0x24 && decSense.Value.ASCQ == 0x00) - { - rawAble = true; - if (decSense.Value.InformationValid && decSense.Value.ILI) - { - longBlockSize = 0xFFFF - (decSense.Value.Information & 0xFFFF); - readLong16 = !dev.ReadLong16(out readBuffer, out senseBuf, false, 0, longBlockSize, dev.Timeout, out duration); - } - } - } - }*/ - - testSense = dev.ReadLong10(out readBuffer, out senseBuf, false, false, 0, 0xFFFF, dev.Timeout, out duration); - if(testSense && !dev.Error) - { - decSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf); - if(decSense.HasValue) - { - if(decSense.Value.SenseKey == Decoders.SCSI.SenseKeys.IllegalRequest && - decSense.Value.ASC == 0x24 && decSense.Value.ASCQ == 0x00) - { - rawAble = true; - if(decSense.Value.InformationValid && decSense.Value.ILI) - { - longBlockSize = 0xFFFF - (decSense.Value.Information & 0xFFFF); - readLong10 = !dev.ReadLong10(out readBuffer, out senseBuf, false, false, 0, (ushort)longBlockSize, dev.Timeout, out duration); - } - } - } - } - - if(rawAble && longBlockSize == blockSize) - { - if(blockSize == 512) - { - // Long sector sizes for 512-byte magneto-opticals - foreach(ushort testSize in new[] { 600, 610, 630 }) - { - testSense = dev.ReadLong16(out readBuffer, out senseBuf, false, 0, testSize, dev.Timeout, out duration); - if(!testSense && !dev.Error) - { - readLong16 = true; - longBlockSize = testSize; - rawAble = true; - break; - } - - testSense = dev.ReadLong10(out readBuffer, out senseBuf, false, false, 0, testSize, dev.Timeout, out duration); - if(!testSense && !dev.Error) - { - readLong10 = true; - longBlockSize = testSize; - rawAble = true; - break; - } - } - } - else if(blockSize == 1024) - { - testSense = dev.ReadLong16(out readBuffer, out senseBuf, false, 0, 1200, dev.Timeout, out duration); - if(!testSense && !dev.Error) - { - readLong16 = true; - longBlockSize = 1200; - rawAble = true; - } - else - { - testSense = dev.ReadLong10(out readBuffer, out senseBuf, false, false, 0, 1200, dev.Timeout, out duration); - if(!testSense && !dev.Error) - { - readLong10 = true; - longBlockSize = 1200; - rawAble = true; - } - } - } - else if(blockSize == 2048) - { - testSense = dev.ReadLong16(out readBuffer, out senseBuf, false, 0, 2380, dev.Timeout, out duration); - if(!testSense && !dev.Error) - { - readLong16 = true; - longBlockSize = 2380; - rawAble = true; - } - else - { - testSense = dev.ReadLong10(out readBuffer, out senseBuf, false, false, 0, 2380, dev.Timeout, out duration); - if(!testSense && !dev.Error) - { - readLong10 = true; - longBlockSize = 2380; - rawAble = true; - } - } - } - else if(blockSize == 4096) - { - testSense = dev.ReadLong16(out readBuffer, out senseBuf, false, 0, 4760, dev.Timeout, out duration); - if(!testSense && !dev.Error) - { - readLong16 = true; - longBlockSize = 4760; - rawAble = true; - } - else - { - testSense = dev.ReadLong10(out readBuffer, out senseBuf, false, false, 0, 4760, dev.Timeout, out duration); - if(!testSense && !dev.Error) - { - readLong10 = true; - longBlockSize = 4760; - rawAble = true; - } - } - } - else if(blockSize == 8192) - { - testSense = dev.ReadLong16(out readBuffer, out senseBuf, false, 0, 9424, dev.Timeout, out duration); - if(!testSense && !dev.Error) - { - readLong16 = true; - longBlockSize = 9424; - rawAble = true; - } - else - { - testSense = dev.ReadLong10(out readBuffer, out senseBuf, false, false, 0, 9424, dev.Timeout, out duration); - if(!testSense && !dev.Error) - { - readLong10 = true; - longBlockSize = 9424; - rawAble = true; - } - } - } - } - - if(!rawAble && dev.Manufacturer == "SYQUEST") - { - testSense = dev.SyQuestReadLong10(out readBuffer, out senseBuf, 0, 0xFFFF, dev.Timeout, out duration); - if(testSense) - { - decSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf); - if(decSense.HasValue) - { - if(decSense.Value.SenseKey == Decoders.SCSI.SenseKeys.IllegalRequest && - decSense.Value.ASC == 0x24 && decSense.Value.ASCQ == 0x00) - { - rawAble = true; - if(decSense.Value.InformationValid && decSense.Value.ILI) - { - longBlockSize = 0xFFFF - (decSense.Value.Information & 0xFFFF); - syqReadLong10 = !dev.SyQuestReadLong10(out readBuffer, out senseBuf, 0, longBlockSize, dev.Timeout, out duration); - } - } - else - { - testSense = dev.SyQuestReadLong6(out readBuffer, out senseBuf, 0, 0xFFFF, dev.Timeout, out duration); - if(testSense) - { - decSense = Decoders.SCSI.Sense.DecodeFixed(senseBuf); - if(decSense.HasValue) - { - if(decSense.Value.SenseKey == Decoders.SCSI.SenseKeys.IllegalRequest && - decSense.Value.ASC == 0x24 && decSense.Value.ASCQ == 0x00) - { - rawAble = true; - if(decSense.Value.InformationValid && decSense.Value.ILI) - { - longBlockSize = 0xFFFF - (decSense.Value.Information & 0xFFFF); - syqReadLong6 = !dev.SyQuestReadLong6(out readBuffer, out senseBuf, 0, longBlockSize, dev.Timeout, out duration); - } - } - } - } - } - } - } - - if(!rawAble && blockSize == 256) - { - testSense = dev.SyQuestReadLong6(out readBuffer, out senseBuf, 0, 262, dev.Timeout, out duration); - if(!testSense && !dev.Error) - { - syqReadLong6 = true; - longBlockSize = 262; - rawAble = true; - } - } - } - } - else - { - if(dev.Manufacturer == "HL-DT-ST") - hldtstReadRaw = !dev.HlDtStReadRawDvd(out readBuffer, out senseBuf, 0, 1, dev.Timeout, out duration); - - if(dev.Manufacturer == "PLEXTOR") - hldtstReadRaw = !dev.PlextorReadRawDvd(out readBuffer, out senseBuf, 0, 1, dev.Timeout, out duration); - - if(hldtstReadRaw || plextorReadRaw) - { - rawAble = true; - longBlockSize = 2064; - } - - // READ LONG (10) for some DVD drives - if(!rawAble && dev.Manufacturer == "MATSHITA") - { - testSense = dev.ReadLong10(out readBuffer, out senseBuf, false, false, 0, 37856, dev.Timeout, out duration); - if(!testSense && !dev.Error) - { - readLongDvd = true; - longBlockSize = 37856; - rawAble = true; - } - } - } - - if(blockSize == longBlockSize) - { - if(!rawAble) - { - DicConsole.ErrorWriteLine("Device doesn't seem capable of reading raw data from media."); - } - else - { - DicConsole.ErrorWriteLine("Device is capable of reading raw data but I've been unable to guess correct sector size."); - } - - if(!options.Force) - { - DicConsole.ErrorWriteLine("Not continuing. If you want to continue reading cooked data when raw is not available use the force option."); - // TODO: Exit more gracefully - return; - } - - DicConsole.ErrorWriteLine("Continuing dumping cooked data."); - options.Raw = false; - } - else - { - if(readLong16) - DicConsole.WriteLine("Using SCSI READ LONG (16) command."); - else if(readLong10 || readLongDvd) - DicConsole.WriteLine("Using SCSI READ LONG (10) command."); - else if(syqReadLong10) - DicConsole.WriteLine("Using SyQuest READ LONG (10) command."); - else if(syqReadLong6) - DicConsole.WriteLine("Using SyQuest READ LONG (6) command."); - else if(hldtstReadRaw) - DicConsole.WriteLine("Using HL-DT-ST raw DVD reading."); - else if(plextorReadRaw) - DicConsole.WriteLine("Using Plextor raw DVD reading."); - else - throw new AccessViolationException("Should not arrive here"); - - if(readLongDvd) // Only a block will be read, but it contains 16 sectors and command expect sector number not block number - blocksToRead = 16; - else - blocksToRead = 1; - DicConsole.WriteLine("Reading {0} raw bytes ({1} cooked bytes) per sector.", - longBlockSize, blockSize * blocksToRead); - physicalBlockSize = longBlockSize; - blockSize = longBlockSize; - } - } - - if(!options.Raw) - { - read6 = !dev.Read6(out readBuffer, out senseBuf, 0, blockSize, dev.Timeout, out duration); - - read10 = !dev.Read10(out readBuffer, out senseBuf, 0, false, true, false, false, 0, blockSize, 0, 1, dev.Timeout, out duration); - - read12 = !dev.Read12(out readBuffer, out senseBuf, 0, false, true, false, false, 0, blockSize, 0, 1, false, dev.Timeout, out duration); - - read16 = !dev.Read16(out readBuffer, out senseBuf, 0, false, true, false, 0, blockSize, 0, 1, false, dev.Timeout, out duration); - - if(!read6 && !read10 && !read12 && !read16) - { - DicConsole.ErrorWriteLine("Cannot read medium, aborting scan..."); - return; - } - - if(read6 && !read10 && !read12 && !read16 && blocks > (0x001FFFFF + 1)) - { - DicConsole.ErrorWriteLine("Device only supports SCSI READ (6) but has more than {0} blocks ({1} blocks total)", 0x001FFFFF + 1, blocks); - return; - } - -#pragma warning disable IDE0004 // Remove Unnecessary Cast - if(!read16 && blocks > ((long)0xFFFFFFFF + (long)1)) -#pragma warning restore IDE0004 // Remove Unnecessary Cast - { -#pragma warning disable IDE0004 // Remove Unnecessary Cast - DicConsole.ErrorWriteLine("Device only supports SCSI READ (10) but has more than {0} blocks ({1} blocks total)", (long)0xFFFFFFFF + (long)1, blocks); -#pragma warning restore IDE0004 // Remove Unnecessary Cast - return; - } - - if(read16) - DicConsole.WriteLine("Using SCSI READ (16) command."); - else if(read12) - DicConsole.WriteLine("Using SCSI READ (12) command."); - else if(read10) - DicConsole.WriteLine("Using SCSI READ (10) command."); - else if(read6) - DicConsole.WriteLine("Using SCSI READ (6) command."); - - while(true) - { - if(read16) - { - sense = dev.Read16(out readBuffer, out senseBuf, 0, false, true, false, 0, blockSize, 0, blocksToRead, false, dev.Timeout, out duration); - if(dev.Error) - blocksToRead /= 2; - } - else if(read12) - { - sense = dev.Read12(out readBuffer, out senseBuf, 0, false, false, false, false, 0, blockSize, 0, blocksToRead, false, dev.Timeout, out duration); - if(dev.Error) - blocksToRead /= 2; - } - else if(read10) - { - sense = dev.Read10(out readBuffer, out senseBuf, 0, false, true, false, false, 0, blockSize, 0, (ushort)blocksToRead, dev.Timeout, out duration); - if(dev.Error) - blocksToRead /= 2; - } - else if(read6) - { - sense = dev.Read6(out readBuffer, out senseBuf, 0, blockSize, (byte)blocksToRead, dev.Timeout, out duration); - if(dev.Error) - blocksToRead /= 2; - } - - if(!dev.Error || blocksToRead == 1) - break; - } - - if(dev.Error) - { - DicConsole.ErrorWriteLine("Device error {0} trying to guess ideal transfer length.", dev.LastError); - return; - } - } - - DicConsole.WriteLine("Reading {0} sectors at a time.", blocksToRead); - - mhddLog = new MHDDLog(options.OutputPrefix + ".mhddlog.bin", dev, blocks, blockSize, blocksToRead); - ibgLog = new IBGLog(options.OutputPrefix + ".ibg", currentProfile); - initDataFile(options.OutputPrefix + ".bin"); - - start = DateTime.UtcNow; - - readBuffer = null; - - for(ulong i = 0; i < blocks; i += blocksToRead) - { - if(aborted) - break; - - double cmdDuration = 0; - - if((blocks - i) < blocksToRead) - blocksToRead = (uint)(blocks - i); - -#pragma warning disable RECS0018 // Comparison of floating point numbers with equality operator - if(currentSpeed > maxSpeed && currentSpeed != 0) - maxSpeed = currentSpeed; - if(currentSpeed < minSpeed && currentSpeed != 0) - minSpeed = currentSpeed; -#pragma warning restore RECS0018 // Comparison of floating point numbers with equality operator - - DicConsole.Write("\rReading sector {0} of {1} ({2:F3} MiB/sec.)", i, blocks, currentSpeed); - - if(readLong16) - { - sense = dev.ReadLong16(out readBuffer, out senseBuf, false, i, blockSize, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - else if(readLong10 || readLongDvd) - { - sense = dev.ReadLong10(out readBuffer, out senseBuf, false, false, (uint)i, (ushort)blockSize, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - else if(syqReadLong10) - { - sense = dev.SyQuestReadLong10(out readBuffer, out senseBuf, (uint)i, blockSize, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - else if(syqReadLong6) - { - sense = dev.SyQuestReadLong6(out readBuffer, out senseBuf, (uint)i, blockSize, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - else if(hldtstReadRaw) - { - sense = dev.HlDtStReadRawDvd(out readBuffer, out senseBuf, (uint)i, blockSize, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - else if(plextorReadRaw) - { - sense = dev.PlextorReadRawDvd(out readBuffer, out senseBuf, (uint)i, blockSize, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - else if(read16) - { - sense = dev.Read16(out readBuffer, out senseBuf, 0, false, true, false, i, blockSize, 0, blocksToRead, false, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - else if(read12) - { - sense = dev.Read12(out readBuffer, out senseBuf, 0, false, false, false, false, (uint)i, blockSize, 0, blocksToRead, false, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - else if(read10) - { - sense = dev.Read10(out readBuffer, out senseBuf, 0, false, true, false, false, (uint)i, blockSize, 0, (ushort)blocksToRead, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - else if(read6) - { - sense = dev.Read6(out readBuffer, out senseBuf, (uint)i, blockSize, (byte)blocksToRead, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - - if(!sense && !dev.Error) - { - mhddLog.Write(i, cmdDuration); - ibgLog.Write(i, currentSpeed * 1024); - writeToDataFile(readBuffer); - } - else - { - // TODO: Reset device after X errors - if(options.StopOnError) - return; // TODO: Return more cleanly - - // Write empty data - writeToDataFile(new byte[blockSize * blocksToRead]); - - // TODO: Record error on mapfile - - errored += blocksToRead; - unreadableSectors.Add(i); - DicConsole.DebugWriteLine("Dump-Media", "READ error:\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); - if(cmdDuration < 500) - mhddLog.Write(i, 65535); - else - mhddLog.Write(i, cmdDuration); - - ibgLog.Write(i, 0); - } - -#pragma warning disable IDE0004 // Remove Unnecessary Cast - currentSpeed = ((double)blockSize * blocksToRead / (double)1048576) / (cmdDuration / (double)1000); -#pragma warning restore IDE0004 // Remove Unnecessary Cast - } - end = DateTime.UtcNow; - DicConsole.WriteLine(); - mhddLog.Close(); -#pragma warning disable IDE0004 // Remove Unnecessary Cast - ibgLog.Close(dev, blocks, blockSize, (end - start).TotalSeconds, currentSpeed * 1024, (((double)blockSize * (double)(blocks + 1)) / 1024) / (totalDuration / 1000), options.DevicePath); -#pragma warning restore IDE0004 // Remove Unnecessary Cast - - #region Error handling - if(unreadableSectors.Count > 0 && !aborted) - { - List tmpList = new List(); - - foreach(ulong ur in unreadableSectors) - { - for(ulong i = ur; i < ur + blocksToRead; i++) - tmpList.Add(i); - } - - tmpList.Sort(); - - int pass = 0; - bool forward = true; - bool runningPersistent = false; - - unreadableSectors = tmpList; - - repeatRetry: - ulong[] tmpArray = unreadableSectors.ToArray(); - foreach(ulong badSector in tmpArray) - { - if(aborted) - break; - - double cmdDuration = 0; - - DicConsole.Write("\rRetrying sector {0}, pass {1}, {3}{2}", badSector, pass + 1, forward ? "forward" : "reverse", runningPersistent ? "recovering partial data, " : ""); - - if(readLong16) - { - sense = dev.ReadLong16(out readBuffer, out senseBuf, false, badSector, blockSize, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - else if(readLong10) - { - sense = dev.ReadLong10(out readBuffer, out senseBuf, false, false, (uint)badSector, (ushort)blockSize, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - else if(syqReadLong10) - { - sense = dev.SyQuestReadLong10(out readBuffer, out senseBuf, (uint)badSector, blockSize, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - else if(syqReadLong6) - { - sense = dev.SyQuestReadLong6(out readBuffer, out senseBuf, (uint)badSector, blockSize, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - else if(hldtstReadRaw) - { - sense = dev.HlDtStReadRawDvd(out readBuffer, out senseBuf, (uint)badSector, blockSize, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - else if(plextorReadRaw) - { - sense = dev.PlextorReadRawDvd(out readBuffer, out senseBuf, (uint)badSector, blockSize, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - else if(read16) - { - sense = dev.Read16(out readBuffer, out senseBuf, 0, false, true, false, badSector, blockSize, 0, 1, false, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - else if(read12) - { - sense = dev.Read12(out readBuffer, out senseBuf, 0, false, false, false, false, (uint)badSector, blockSize, 0, 1, false, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - else if(read10) - { - sense = dev.Read10(out readBuffer, out senseBuf, 0, false, true, false, false, (uint)badSector, blockSize, 0, 1, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - else if(read6) - { - sense = dev.Read6(out readBuffer, out senseBuf, (uint)badSector, blockSize, 1, dev.Timeout, out cmdDuration); - totalDuration += cmdDuration; - } - - if(!sense && !dev.Error) - { - unreadableSectors.Remove(badSector); - writeToDataFileAtPosition(readBuffer, badSector, blockSize); - } - else if(runningPersistent) - writeToDataFileAtPosition(readBuffer, badSector, blockSize); - } - - if(pass < options.RetryPasses && !aborted && unreadableSectors.Count > 0) - { - pass++; - forward = !forward; - unreadableSectors.Sort(); - unreadableSectors.Reverse(); - goto repeatRetry; - } - - Decoders.SCSI.Modes.DecodedMode? currentMode = null; - Decoders.SCSI.Modes.ModePage? currentModePage = null; - byte[] md6 = null; - byte[] md10 = null; - - if(!runningPersistent && options.Persistent) - { - sense = dev.ModeSense6(out readBuffer, out senseBuf, false, ScsiModeSensePageControl.Current, 0x01, dev.Timeout, out duration); - if(sense) - { - sense = dev.ModeSense10(out readBuffer, out senseBuf, false, ScsiModeSensePageControl.Current, 0x01, dev.Timeout, out duration); - if(!sense) - currentMode = Decoders.SCSI.Modes.DecodeMode10(readBuffer, dev.SCSIType); - } - else - currentMode = Decoders.SCSI.Modes.DecodeMode6(readBuffer, dev.SCSIType); - - if(currentMode.HasValue) - currentModePage = currentMode.Value.Pages[0]; - - if(dev.SCSIType == Decoders.SCSI.PeripheralDeviceTypes.MultiMediaDevice) - { - Decoders.SCSI.Modes.ModePage_01_MMC pgMMC = new Decoders.SCSI.Modes.ModePage_01_MMC(); - pgMMC.PS = false; - pgMMC.ReadRetryCount = 255; - pgMMC.Parameter = 0x20; - - Decoders.SCSI.Modes.DecodedMode md = new Decoders.SCSI.Modes.DecodedMode(); - md.Header = new Decoders.SCSI.Modes.ModeHeader(); - md.Pages = new Decoders.SCSI.Modes.ModePage[1]; - md.Pages[0] = new Decoders.SCSI.Modes.ModePage(); - md.Pages[0].Page = 0x01; - md.Pages[0].Subpage = 0x00; - md.Pages[0].PageResponse = Decoders.SCSI.Modes.EncodeModePage_01_MMC(pgMMC); - md6 = Decoders.SCSI.Modes.EncodeMode6(md, dev.SCSIType); - md10 = Decoders.SCSI.Modes.EncodeMode10(md, dev.SCSIType); - } - else - { - Decoders.SCSI.Modes.ModePage_01 pg = new Decoders.SCSI.Modes.ModePage_01(); - pg.PS = false; - pg.AWRE = false; - pg.ARRE = false; - pg.TB = true; - pg.RC = false; - pg.EER = true; - pg.PER = false; - pg.DTE = false; - pg.DCR = false; - pg.ReadRetryCount = 255; - - Decoders.SCSI.Modes.DecodedMode md = new Decoders.SCSI.Modes.DecodedMode(); - md.Header = new Decoders.SCSI.Modes.ModeHeader(); - md.Pages = new Decoders.SCSI.Modes.ModePage[1]; - md.Pages[0] = new Decoders.SCSI.Modes.ModePage(); - md.Pages[0].Page = 0x01; - md.Pages[0].Subpage = 0x00; - md.Pages[0].PageResponse = Decoders.SCSI.Modes.EncodeModePage_01(pg); - md6 = Decoders.SCSI.Modes.EncodeMode6(md, dev.SCSIType); - md10 = Decoders.SCSI.Modes.EncodeMode10(md, dev.SCSIType); - } - - sense = dev.ModeSelect(md6, out senseBuf, true, false, dev.Timeout, out duration); - if(sense) - { - sense = dev.ModeSelect10(md10, out senseBuf, true, false, dev.Timeout, out duration); - } - - runningPersistent = true; - if(!sense && !dev.Error) - { - pass--; - goto repeatRetry; - } - } - else if(runningPersistent && options.Persistent && currentModePage.HasValue) - { - Decoders.SCSI.Modes.DecodedMode md = new Decoders.SCSI.Modes.DecodedMode(); - md.Header = new Decoders.SCSI.Modes.ModeHeader(); - md.Pages = new Decoders.SCSI.Modes.ModePage[1]; - md.Pages[0] = currentModePage.Value; - md6 = Decoders.SCSI.Modes.EncodeMode6(md, dev.SCSIType); - md10 = Decoders.SCSI.Modes.EncodeMode10(md, dev.SCSIType); - - sense = dev.ModeSelect(md6, out senseBuf, true, false, dev.Timeout, out duration); - if(sense) - { - sense = dev.ModeSelect10(md10, out senseBuf, true, false, dev.Timeout, out duration); - } - } - - DicConsole.WriteLine(); - } - #endregion Error handling - - dataChk = new Core.Checksum(); - dataFs.Seek(0, SeekOrigin.Begin); - blocksToRead = 500; - - for(ulong i = 0; i < blocks; i += blocksToRead) - { - if(aborted) - break; - - if((blocks - i) < blocksToRead) - blocksToRead = (uint)(blocks - i); - - DicConsole.Write("\rChecksumming sector {0} of {1} ({2:F3} MiB/sec.)", i, blocks, currentSpeed); - - DateTime chkStart = DateTime.UtcNow; - byte[] dataToCheck = new byte[blockSize * blocksToRead]; - dataFs.Read(dataToCheck, 0, (int)(blockSize * blocksToRead)); - dataChk.Update(dataToCheck); - DateTime chkEnd = DateTime.UtcNow; - - double chkDuration = (chkEnd - chkStart).TotalMilliseconds; - totalChkDuration += chkDuration; - -#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created - currentSpeed = ((double)blockSize * blocksToRead / (double)1048576) / (chkDuration / (double)1000); -#pragma warning restore IDE0004 // Cast is necessary, otherwise incorrect value is created - } - DicConsole.WriteLine(); - closeDataFile(); - end = DateTime.UtcNow; - - PluginBase plugins = new PluginBase(); - plugins.RegisterAllPlugins(); - ImagePlugin _imageFormat; - FiltersList filtersList = new FiltersList(); - Filter inputFilter = filtersList.GetFilter(options.OutputPrefix + ".bin"); - - if(inputFilter == null) - { - DicConsole.ErrorWriteLine("Cannot open file just created, this should not happen."); - return; - } - - _imageFormat = ImageFormat.Detect(inputFilter); - PartitionType[] xmlFileSysInfo = null; - - try - { - if(!_imageFormat.OpenImage(inputFilter)) - _imageFormat = null; - } - catch - { - _imageFormat = null; - } - - if(_imageFormat != null) - { - List partitions = new List(); - - foreach(PartPlugin _partplugin in plugins.PartPluginsList.Values) - { - List _partitions; - - if(_partplugin.GetInformation(_imageFormat, out _partitions)) - { - partitions.AddRange(_partitions); - Core.Statistics.AddPartition(_partplugin.Name); - } - } - - if(partitions.Count > 0) - { - xmlFileSysInfo = new PartitionType[partitions.Count]; - for(int i = 0; i < partitions.Count; i++) - { - xmlFileSysInfo[i] = new PartitionType(); - xmlFileSysInfo[i].Description = partitions[i].PartitionDescription; - xmlFileSysInfo[i].EndSector = (int)(partitions[i].PartitionStartSector + partitions[i].PartitionSectors - 1); - xmlFileSysInfo[i].Name = partitions[i].PartitionName; - xmlFileSysInfo[i].Sequence = (int)partitions[i].PartitionSequence; - xmlFileSysInfo[i].StartSector = (int)partitions[i].PartitionStartSector; - xmlFileSysInfo[i].Type = partitions[i].PartitionType; - - List lstFs = new List(); - - foreach(Filesystem _plugin in plugins.PluginsList.Values) - { - try - { - if(_plugin.Identify(_imageFormat, partitions[i].PartitionStartSector, partitions[i].PartitionStartSector + partitions[i].PartitionSectors - 1)) - { - string foo; - _plugin.GetInformation(_imageFormat, partitions[i].PartitionStartSector, partitions[i].PartitionStartSector + partitions[i].PartitionSectors - 1, out foo); - lstFs.Add(_plugin.XmlFSType); - Core.Statistics.AddFilesystem(_plugin.XmlFSType.Type); - - if(_plugin.XmlFSType.Type == "Opera") - dskType = MediaType.ThreeDO; - if(_plugin.XmlFSType.Type == "PC Engine filesystem") - dskType = MediaType.SuperCDROM2; - if(_plugin.XmlFSType.Type == "Nintendo Wii filesystem") - dskType = MediaType.WOD; - if(_plugin.XmlFSType.Type == "Nintendo Gamecube filesystem") - dskType = MediaType.GOD; - } - } -#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body - catch -#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body - { - //DicConsole.DebugWriteLine("Dump-media command", "Plugin {0} crashed", _plugin.Name); - } - } - - if(lstFs.Count > 0) - xmlFileSysInfo[i].FileSystems = lstFs.ToArray(); - } - } - else - { - xmlFileSysInfo = new PartitionType[1]; - xmlFileSysInfo[0] = new PartitionType(); - xmlFileSysInfo[0].EndSector = (int)(blocks - 1); - xmlFileSysInfo[0].StartSector = 0; - - List lstFs = new List(); - - foreach(Filesystem _plugin in plugins.PluginsList.Values) - { - try - { - if(_plugin.Identify(_imageFormat, (blocks - 1), 0)) - { - string foo; - _plugin.GetInformation(_imageFormat, (blocks - 1), 0, out foo); - lstFs.Add(_plugin.XmlFSType); - Core.Statistics.AddFilesystem(_plugin.XmlFSType.Type); - - if(_plugin.XmlFSType.Type == "Opera") - dskType = MediaType.ThreeDO; - if(_plugin.XmlFSType.Type == "PC Engine filesystem") - dskType = MediaType.SuperCDROM2; - if(_plugin.XmlFSType.Type == "Nintendo Wii filesystem") - dskType = MediaType.WOD; - if(_plugin.XmlFSType.Type == "Nintendo Gamecube filesystem") - dskType = MediaType.GOD; - } - } -#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body - catch -#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body - { - //DicConsole.DebugWriteLine("Create-sidecar command", "Plugin {0} crashed", _plugin.Name); - } - } - - if(lstFs.Count > 0) - xmlFileSysInfo[0].FileSystems = lstFs.ToArray(); - } - } - - if(opticalDisc) - { - sidecar.OpticalDisc[0].Checksums = dataChk.End().ToArray(); - sidecar.OpticalDisc[0].DumpHardwareArray = new DumpHardwareType[1]; - sidecar.OpticalDisc[0].DumpHardwareArray[0] = new DumpHardwareType(); - sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents = new ExtentType[1]; - sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents[0] = new ExtentType(); - sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents[0].Start = 0; - sidecar.OpticalDisc[0].DumpHardwareArray[0].Extents[0].End = (int)(blocks - 1); - sidecar.OpticalDisc[0].DumpHardwareArray[0].Manufacturer = dev.Manufacturer; - sidecar.OpticalDisc[0].DumpHardwareArray[0].Model = dev.Model; - sidecar.OpticalDisc[0].DumpHardwareArray[0].Revision = dev.Revision; - sidecar.OpticalDisc[0].DumpHardwareArray[0].Software = new SoftwareType(); - sidecar.OpticalDisc[0].DumpHardwareArray[0].Software.Name = "DiscImageChef"; - sidecar.OpticalDisc[0].DumpHardwareArray[0].Software.OperatingSystem = dev.PlatformID.ToString(); - sidecar.OpticalDisc[0].DumpHardwareArray[0].Software.Version = typeof(MainClass).Assembly.GetName().Version.ToString(); - sidecar.OpticalDisc[0].Image = new ImageType(); - sidecar.OpticalDisc[0].Image.format = "Raw disk image (sector by sector copy)"; - sidecar.OpticalDisc[0].Image.Value = options.OutputPrefix + ".bin"; - // TODO: Implement layers - //sidecar.OpticalDisc[0].Layers = new LayersType(); - sidecar.OpticalDisc[0].Sessions = 1; - sidecar.OpticalDisc[0].Tracks = new[] { 1 }; - sidecar.OpticalDisc[0].Track = new Schemas.TrackType[1]; - sidecar.OpticalDisc[0].Track[0] = new Schemas.TrackType(); - sidecar.OpticalDisc[0].Track[0].BytesPerSector = (int)blockSize; - sidecar.OpticalDisc[0].Track[0].Checksums = sidecar.OpticalDisc[0].Checksums; - sidecar.OpticalDisc[0].Track[0].EndSector = (long)(blocks - 1); - sidecar.OpticalDisc[0].Track[0].Image = new ImageType(); - sidecar.OpticalDisc[0].Track[0].Image.format = "BINARY"; - sidecar.OpticalDisc[0].Track[0].Image.offset = 0; - sidecar.OpticalDisc[0].Track[0].Image.offsetSpecified = true; - sidecar.OpticalDisc[0].Track[0].Image.Value = sidecar.OpticalDisc[0].Image.Value; - sidecar.OpticalDisc[0].Track[0].Sequence = new TrackSequenceType(); - sidecar.OpticalDisc[0].Track[0].Sequence.Session = 1; - sidecar.OpticalDisc[0].Track[0].Sequence.TrackNumber = 1; - sidecar.OpticalDisc[0].Track[0].Size = (long)(blocks * blockSize); - sidecar.OpticalDisc[0].Track[0].StartSector = 0; - if(xmlFileSysInfo != null) - sidecar.OpticalDisc[0].Track[0].FileSystemInformation = xmlFileSysInfo; - switch(dskType) - { - case MediaType.DDCD: - case MediaType.DDCDR: - case MediaType.DDCDRW: - sidecar.OpticalDisc[0].Track[0].TrackType1 = TrackTypeTrackType.ddcd; - break; - case MediaType.DVDROM: - case MediaType.DVDR: - case MediaType.DVDRAM: - case MediaType.DVDRW: - case MediaType.DVDRDL: - case MediaType.DVDRWDL: - case MediaType.DVDDownload: - case MediaType.DVDPRW: - case MediaType.DVDPR: - case MediaType.DVDPRWDL: - case MediaType.DVDPRDL: - sidecar.OpticalDisc[0].Track[0].TrackType1 = TrackTypeTrackType.dvd; - break; - case MediaType.HDDVDROM: - case MediaType.HDDVDR: - case MediaType.HDDVDRAM: - case MediaType.HDDVDRW: - case MediaType.HDDVDRDL: - case MediaType.HDDVDRWDL: - sidecar.OpticalDisc[0].Track[0].TrackType1 = TrackTypeTrackType.hddvd; - break; - case MediaType.BDROM: - case MediaType.BDR: - case MediaType.BDRE: - case MediaType.BDREXL: - case MediaType.BDRXL: - sidecar.OpticalDisc[0].Track[0].TrackType1 = TrackTypeTrackType.bluray; - break; - } - sidecar.OpticalDisc[0].Dimensions = Metadata.Dimensions.DimensionsFromMediaType(dskType); - string xmlDskTyp, xmlDskSubTyp; - Metadata.MediaType.MediaTypeToString(dskType, out xmlDskTyp, out xmlDskSubTyp); - sidecar.OpticalDisc[0].DiscType = xmlDskTyp; - sidecar.OpticalDisc[0].DiscSubType = xmlDskSubTyp; - } - else - { - sidecar.BlockMedia[0].Checksums = dataChk.End().ToArray(); - sidecar.BlockMedia[0].Dimensions = Metadata.Dimensions.DimensionsFromMediaType(dskType); - string xmlDskTyp, xmlDskSubTyp; - Metadata.MediaType.MediaTypeToString(dskType, out xmlDskTyp, out xmlDskSubTyp); - sidecar.BlockMedia[0].DiskType = xmlDskTyp; - sidecar.BlockMedia[0].DiskSubType = xmlDskSubTyp; - // TODO: Implement device firmware revision - sidecar.BlockMedia[0].Image = new ImageType(); - sidecar.BlockMedia[0].Image.format = "Raw disk image (sector by sector copy)"; - sidecar.BlockMedia[0].Image.Value = options.OutputPrefix + ".bin"; - if(!dev.IsRemovable || dev.IsUSB) - { - if(dev.Type == DeviceType.ATAPI) - sidecar.BlockMedia[0].Interface = "ATAPI"; - else if(dev.IsUSB) - sidecar.BlockMedia[0].Interface = "USB"; - else if(dev.IsFireWire) - sidecar.BlockMedia[0].Interface = "FireWire"; - else - sidecar.BlockMedia[0].Interface = "SCSI"; - } - sidecar.BlockMedia[0].LogicalBlocks = (long)blocks; - sidecar.BlockMedia[0].PhysicalBlockSize = (int)physicalBlockSize; - sidecar.BlockMedia[0].LogicalBlockSize = (int)logicalBlockSize; - sidecar.BlockMedia[0].Manufacturer = dev.Manufacturer; - sidecar.BlockMedia[0].Model = dev.Model; - sidecar.BlockMedia[0].Serial = dev.Serial; - sidecar.BlockMedia[0].Size = (long)(blocks * blockSize); - if(xmlFileSysInfo != null) - sidecar.BlockMedia[0].FileSystemInformation = xmlFileSysInfo; - - if(dev.IsRemovable) - { - sidecar.BlockMedia[0].DumpHardwareArray = new DumpHardwareType[1]; - sidecar.BlockMedia[0].DumpHardwareArray[0] = new DumpHardwareType(); - sidecar.BlockMedia[0].DumpHardwareArray[0].Extents = new ExtentType[1]; - sidecar.BlockMedia[0].DumpHardwareArray[0].Extents[0] = new ExtentType(); - sidecar.BlockMedia[0].DumpHardwareArray[0].Extents[0].Start = 0; - sidecar.BlockMedia[0].DumpHardwareArray[0].Extents[0].End = (int)(blocks - 1); - sidecar.BlockMedia[0].DumpHardwareArray[0].Manufacturer = dev.Manufacturer; - sidecar.BlockMedia[0].DumpHardwareArray[0].Model = dev.Model; - sidecar.BlockMedia[0].DumpHardwareArray[0].Revision = dev.Revision; - sidecar.BlockMedia[0].DumpHardwareArray[0].Software = new SoftwareType(); - sidecar.BlockMedia[0].DumpHardwareArray[0].Software.Name = "DiscImageChef"; - sidecar.BlockMedia[0].DumpHardwareArray[0].Software.OperatingSystem = dev.PlatformID.ToString(); - sidecar.BlockMedia[0].DumpHardwareArray[0].Software.Version = typeof(MainClass).Assembly.GetName().Version.ToString(); - } - } - } - - DicConsole.WriteLine(); - - DicConsole.WriteLine("Took a total of {0:F3} seconds ({1:F3} processing commands, {2:F3} checksumming).", (end - start).TotalSeconds, totalDuration / 1000, totalChkDuration / 1000); -#pragma warning disable IDE0004 // Cast is necessary, otherwise incorrect value is created - DicConsole.WriteLine("Avegare speed: {0:F3} MiB/sec.", (((double)blockSize * (double)(blocks + 1)) / 1048576) / (totalDuration / 1000)); -#pragma warning restore IDE0004 // Cast is necessary, otherwise incorrect value is created - DicConsole.WriteLine("Fastest speed burst: {0:F3} MiB/sec.", maxSpeed); - DicConsole.WriteLine("Slowest speed burst: {0:F3} MiB/sec.", minSpeed); - DicConsole.WriteLine("{0} sectors could not be read.", unreadableSectors.Count); - if(unreadableSectors.Count > 0) - { - unreadableSectors.Sort(); - foreach(ulong bad in unreadableSectors) - DicConsole.WriteLine("Sector {0} could not be read", bad); - } - DicConsole.WriteLine(); - - if(!aborted) - { - DicConsole.WriteLine("Writing metadata sidecar"); - - FileStream xmlFs = new FileStream(options.OutputPrefix + ".cicm.xml", - FileMode.Create); - - System.Xml.Serialization.XmlSerializer xmlSer = new System.Xml.Serialization.XmlSerializer(typeof(CICMMetadataType)); - xmlSer.Serialize(xmlFs, sidecar); - xmlFs.Close(); - } - - Core.Statistics.AddMedia(dskType, true); - } - - static void writeToFile(string file, byte[] data) - { - FileStream fs = new FileStream(file, FileMode.Create, FileAccess.ReadWrite); - fs.Write(data, 0, data.Length); - fs.Close(); - } - - static void initDataFile(string outputFile) - { - dataFs = new FileStream(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite); - } - - static void writeToDataFile(byte[] data) - { - dataFs.Write(data, 0, data.Length); - } - - static void writeToDataFileAtPosition(byte[] data, ulong block, uint blockSize) - { - dataFs.Seek((long)(block * blockSize), SeekOrigin.Begin); - dataFs.Write(data, 0, data.Length); - } - - static void closeDataFile() - { - if(dataFs != null) - dataFs.Close(); - } } } \ No newline at end of file diff --git a/DiscImageChef/Commands/MediaInfo.cs b/DiscImageChef/Commands/MediaInfo.cs index 810939695..cff88f1c9 100644 --- a/DiscImageChef/Commands/MediaInfo.cs +++ b/DiscImageChef/Commands/MediaInfo.cs @@ -36,6 +36,7 @@ using System.IO; using DiscImageChef.Devices; using DiscImageChef.CommonTypes; using System.Linq; +using DiscImageChef.Core; namespace DiscImageChef.Commands { @@ -208,7 +209,7 @@ namespace DiscImageChef.Commands } if(!sense) - doWriteFile(outputPrefix, "_scsi_modesense.bin", "SCSI MODE SENSE", modeBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_scsi_modesense.bin", "SCSI MODE SENSE", modeBuf); byte scsiMediumType = 0; byte scsiDensityCode = 0; @@ -234,7 +235,7 @@ namespace DiscImageChef.Commands sense = dev.ReadCapacity(out cmdBuf, out senseBuf, dev.Timeout, out duration); if(!sense) { - doWriteFile(outputPrefix, "_readcapacity.bin", "SCSI READ CAPACITY", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readcapacity.bin", "SCSI READ CAPACITY", cmdBuf); blocks = (ulong)((cmdBuf[0] << 24) + (cmdBuf[1] << 16) + (cmdBuf[2] << 8) + (cmdBuf[3])); blockSize = (uint)((cmdBuf[5] << 24) + (cmdBuf[5] << 16) + (cmdBuf[6] << 8) + (cmdBuf[7])); } @@ -255,7 +256,7 @@ namespace DiscImageChef.Commands if(!sense) { - doWriteFile(outputPrefix, "_readcapacity16.bin", "SCSI READ CAPACITY(16)", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readcapacity16.bin", "SCSI READ CAPACITY(16)", cmdBuf); byte[] temp = new byte[8]; Array.Copy(cmdBuf, 0, temp, 0, 8); @@ -285,7 +286,7 @@ namespace DiscImageChef.Commands if(!sense && !seqBuf.SequenceEqual(medBuf)) { - doWriteFile(outputPrefix, "_ssc_reportdensitysupport_media.bin", "SSC REPORT DENSITY SUPPORT (MEDIA)", seqBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_ssc_reportdensitysupport_media.bin", "SSC REPORT DENSITY SUPPORT (MEDIA)", seqBuf); Decoders.SCSI.SSC.DensitySupport.DensitySupportHeader? dens = Decoders.SCSI.SSC.DensitySupport.DecodeDensity(seqBuf); if(dens.HasValue) { @@ -302,7 +303,7 @@ namespace DiscImageChef.Commands if(!sense && !seqBuf.SequenceEqual(medBuf)) { - doWriteFile(outputPrefix, "_ssc_reportdensitysupport_medium_media.bin", "SSC REPORT DENSITY SUPPORT (MEDIUM & MEDIA)", seqBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_ssc_reportdensitysupport_medium_media.bin", "SSC REPORT DENSITY SUPPORT (MEDIUM & MEDIA)", seqBuf); Decoders.SCSI.SSC.DensitySupport.MediaTypeSupportHeader? meds = Decoders.SCSI.SSC.DensitySupport.DecodeMediumType(seqBuf); if(meds.HasValue) { @@ -320,7 +321,7 @@ namespace DiscImageChef.Commands DicConsole.ErrorWriteLine("SCSI READ ATTRIBUTE:\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(outputPrefix, "_scsi_readattribute.bin", "SCSI READ ATTRIBUTE", seqBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_scsi_readattribute.bin", "SCSI READ ATTRIBUTE", seqBuf); } */ } @@ -332,7 +333,7 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Media-Info command", "READ GET CONFIGURATION:\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(outputPrefix, "_getconfiguration_current.bin", "SCSI GET CONFIGURATION", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_getconfiguration_current.bin", "SCSI GET CONFIGURATION", cmdBuf); Decoders.SCSI.MMC.Features.SeparatedFeatures ftr = Decoders.SCSI.MMC.Features.Separate(cmdBuf); @@ -434,12 +435,12 @@ namespace DiscImageChef.Commands if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: Recognized Format Layers\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_formatlayers.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_formatlayers.bin", "SCSI READ DISC STRUCTURE", cmdBuf); sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.WriteProtectionStatus, 0, dev.Timeout, out duration); if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: Write Protection Status\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_writeprotection.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_writeprotection.bin", "SCSI READ DISC STRUCTURE", cmdBuf); // More like a drive information /* @@ -447,7 +448,7 @@ namespace DiscImageChef.Commands if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: Capability List\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_capabilitylist.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_capabilitylist.bin", "SCSI READ DISC STRUCTURE", cmdBuf); */ #region All DVD and HD DVD types @@ -467,7 +468,7 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: PFI\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(outputPrefix, "_readdiscstructure_dvd_pfi.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_pfi.bin", "SCSI READ DISC STRUCTURE", cmdBuf); Decoders.DVD.PFI.PhysicalFormatInformation? decPfi = Decoders.DVD.PFI.Decode(cmdBuf); if(decPfi.HasValue) { @@ -538,7 +539,7 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: DMI\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(outputPrefix, "_readdiscstructure_dvd_dmi.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_dmi.bin", "SCSI READ DISC STRUCTURE", cmdBuf); if(Decoders.Xbox.DMI.IsXbox(cmdBuf)) { dskType = MediaType.XGD; @@ -567,7 +568,7 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: CMI\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(outputPrefix, "_readdiscstructure_dvd_cmi.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_cmi.bin", "SCSI READ DISC STRUCTURE", cmdBuf); DicConsole.WriteLine("Lead-In CMI:\n{0}", Decoders.DVD.CSS_CPRM.PrettifyLeadInCopyright(cmdBuf)); } } @@ -581,12 +582,12 @@ namespace DiscImageChef.Commands if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: BCA\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_dvd_bca.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_bca.bin", "SCSI READ DISC STRUCTURE", cmdBuf); sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.DVD_AACS, 0, dev.Timeout, out duration); if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: DVD AACS\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_dvd_aacs.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_aacs.bin", "SCSI READ DISC STRUCTURE", cmdBuf); } #endregion DVD-ROM and HD DVD-ROM @@ -596,57 +597,57 @@ namespace DiscImageChef.Commands if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: Disc Key\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_dvd_disckey.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_disckey.bin", "SCSI READ DISC STRUCTURE", cmdBuf); sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.SectorCopyrightInformation, 0, dev.Timeout, out duration); if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: Sector CMI\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_dvd_sectorcmi.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_sectorcmi.bin", "SCSI READ DISC STRUCTURE", cmdBuf); sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.MediaIdentifier, 0, dev.Timeout, out duration); if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: Media ID\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_dvd_mediaid.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_mediaid.bin", "SCSI READ DISC STRUCTURE", cmdBuf); sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.MediaKeyBlock, 0, dev.Timeout, out duration); if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: MKB\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_dvd_mkb.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_mkb.bin", "SCSI READ DISC STRUCTURE", cmdBuf); sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.AACSVolId, 0, dev.Timeout, out duration); if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: AACS Volume ID\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_aacsvolid.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_aacsvolid.bin", "SCSI READ DISC STRUCTURE", cmdBuf); sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.AACSMediaSerial, 0, dev.Timeout, out duration); if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: AACS Media Serial Number\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_aacssn.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_aacssn.bin", "SCSI READ DISC STRUCTURE", cmdBuf); sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.AACSMediaId, 0, dev.Timeout, out duration); if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: AACS Media ID\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_aacsmediaid.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_aacsmediaid.bin", "SCSI READ DISC STRUCTURE", cmdBuf); sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.AACSMKB, 0, dev.Timeout, out duration); if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: AACS MKB\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_aacsmkb.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_aacsmkb.bin", "SCSI READ DISC STRUCTURE", cmdBuf); sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.AACSLBAExtents, 0, dev.Timeout, out duration); if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: AACS LBA Extents\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_aacslbaextents.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_aacslbaextents.bin", "SCSI READ DISC STRUCTURE", cmdBuf); sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.AACSMKBCPRM, 0, dev.Timeout, out duration); if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: AACS CPRM MKB\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_aacscprmmkb.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_aacscprmmkb.bin", "SCSI READ DISC STRUCTURE", cmdBuf); sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.AACSDataKeys, 0, dev.Timeout, out duration); if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: AACS Data Keys\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_aacsdatakeys.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_aacsdatakeys.bin", "SCSI READ DISC STRUCTURE", cmdBuf); */ #endregion Require drive authentication, won't work @@ -658,7 +659,7 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: DDS\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(outputPrefix, "_readdiscstructure_dvdram_dds.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdram_dds.bin", "SCSI READ DISC STRUCTURE", cmdBuf); DicConsole.WriteLine("Disc Definition Structure:\n{0}", Decoders.DVD.DDS.Prettify(cmdBuf)); } sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.DVDRAM_MediumStatus, 0, dev.Timeout, out duration); @@ -666,7 +667,7 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: Medium Status\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(outputPrefix, "_readdiscstructure_dvdram_status.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdram_status.bin", "SCSI READ DISC STRUCTURE", cmdBuf); DicConsole.WriteLine("Medium Status:\n{0}", Decoders.DVD.Cartridge.Prettify(cmdBuf)); } sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.DVDRAM_SpareAreaInformation, 0, dev.Timeout, out duration); @@ -674,7 +675,7 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: SAI\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(outputPrefix, "_readdiscstructure_dvdram_spare.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdram_spare.bin", "SCSI READ DISC STRUCTURE", cmdBuf); DicConsole.WriteLine("Spare Area Information:\n{0}", Decoders.DVD.Spare.Prettify(cmdBuf)); } } @@ -687,7 +688,7 @@ namespace DiscImageChef.Commands if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: Last-Out Border RMD\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_dvd_lastrmd.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_lastrmd.bin", "SCSI READ DISC STRUCTURE", cmdBuf); } #endregion DVD-R and HD DVD-R @@ -698,7 +699,7 @@ namespace DiscImageChef.Commands if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: Pre-Recorded Info\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_dvd_pri.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_pri.bin", "SCSI READ DISC STRUCTURE", cmdBuf); } #endregion DVD-R and DVD-RW @@ -709,12 +710,12 @@ namespace DiscImageChef.Commands if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: DVD-R Media ID\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_dvdr_mediaid.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdr_mediaid.bin", "SCSI READ DISC STRUCTURE", cmdBuf); sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.DVDR_PhysicalInformation, 0, dev.Timeout, out duration); if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: DVD-R PFI\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_dvdr_pfi.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdr_pfi.bin", "SCSI READ DISC STRUCTURE", cmdBuf); } #endregion DVD-R, DVD-RW and HD DVD-R @@ -726,13 +727,13 @@ namespace DiscImageChef.Commands if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: ADIP\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_dvd+_adip.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd+_adip.bin", "SCSI READ DISC STRUCTURE", cmdBuf); sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.DCB, 0, dev.Timeout, out duration); if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: DCB\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_dvd+_dcb.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd+_dcb.bin", "SCSI READ DISC STRUCTURE", cmdBuf); } #endregion All DVD+ @@ -743,7 +744,7 @@ namespace DiscImageChef.Commands if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: HDDVD CMI\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_hddvd_cmi.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_hddvd_cmi.bin", "SCSI READ DISC STRUCTURE", cmdBuf); } #endregion HD DVD-ROM @@ -754,12 +755,12 @@ namespace DiscImageChef.Commands if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: HDDVD-R Medium Status\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_hddvdr_status.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_hddvdr_status.bin", "SCSI READ DISC STRUCTURE", cmdBuf); sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.HDDVDR_LastRMD, 0, dev.Timeout, out duration); if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: Last RMD\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_hddvdr_lastrmd.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_hddvdr_lastrmd.bin", "SCSI READ DISC STRUCTURE", cmdBuf); } #endregion HD DVD-R @@ -771,7 +772,7 @@ namespace DiscImageChef.Commands if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: Layer Capacity\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_dvdr_layercap.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdr_layercap.bin", "SCSI READ DISC STRUCTURE", cmdBuf); } #endregion DVD-R DL, DVD-RW DL, DVD+R DL, DVD+RW DL @@ -782,22 +783,22 @@ namespace DiscImageChef.Commands if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: Middle Zone Start\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_dvd_mzs.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_mzs.bin", "SCSI READ DISC STRUCTURE", cmdBuf); sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.JumpIntervalSize, 0, dev.Timeout, out duration); if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: Jump Interval Size\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_dvd_jis.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_jis.bin", "SCSI READ DISC STRUCTURE", cmdBuf); sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.ManualLayerJumpStartLBA, 0, dev.Timeout, out duration); if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: Manual Layer Jump Start LBA\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_dvd_manuallj.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_manuallj.bin", "SCSI READ DISC STRUCTURE", cmdBuf); sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.DVD, 0, 0, MmcDiscStructureFormat.RemapAnchorPoint, 0, dev.Timeout, out duration); if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: Remap Anchor Point\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_dvd_remapanchor.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_remapanchor.bin", "SCSI READ DISC STRUCTURE", cmdBuf); } #endregion DVD-R DL @@ -810,14 +811,14 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: DI\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(outputPrefix, "_readdiscstructure_bd_di.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_di.bin", "SCSI READ DISC STRUCTURE", cmdBuf); DicConsole.WriteLine("Blu-ray Disc Information:\n{0}", Decoders.Bluray.DI.Prettify(cmdBuf)); } sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.BD, 0, 0, MmcDiscStructureFormat.PAC, 0, dev.Timeout, out duration); if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: PAC\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_bd_pac.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_pac.bin", "SCSI READ DISC STRUCTURE", cmdBuf); } #endregion All Blu-ray @@ -829,7 +830,7 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: BCA\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(outputPrefix, "_readdiscstructure_bd_bca.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_bca.bin", "SCSI READ DISC STRUCTURE", cmdBuf); DicConsole.WriteLine("Blu-ray Burst Cutting Area:\n{0}", Decoders.Bluray.BCA.Prettify(cmdBuf)); } } @@ -844,7 +845,7 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: DDS\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(outputPrefix, "_readdiscstructure_bd_dds.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_dds.bin", "SCSI READ DISC STRUCTURE", cmdBuf); DicConsole.WriteLine("Blu-ray Disc Definition Structure:\n{0}", Decoders.Bluray.DDS.Prettify(cmdBuf)); } sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.BD, 0, 0, MmcDiscStructureFormat.CartridgeStatus, 0, dev.Timeout, out duration); @@ -852,7 +853,7 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: Cartridge Status\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(outputPrefix, "_readdiscstructure_bd_cartstatus.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_cartstatus.bin", "SCSI READ DISC STRUCTURE", cmdBuf); DicConsole.WriteLine("Blu-ray Cartridge Status:\n{0}", Decoders.Bluray.DI.Prettify(cmdBuf)); } sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.BD, 0, 0, MmcDiscStructureFormat.BD_SpareAreaInformation, 0, dev.Timeout, out duration); @@ -860,21 +861,21 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: Spare Area Information\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(outputPrefix, "_readdiscstructure_bd_spare.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_spare.bin", "SCSI READ DISC STRUCTURE", cmdBuf); DicConsole.WriteLine("Blu-ray Spare Area Information:\n{0}", Decoders.Bluray.DI.Prettify(cmdBuf)); } sense = dev.ReadDiscStructure(out cmdBuf, out senseBuf, MmcDiscStructureMediaType.BD, 0, 0, MmcDiscStructureFormat.RawDFL, 0, dev.Timeout, out duration); if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: Raw DFL\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_bd_dfl.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_dfl.bin", "SCSI READ DISC STRUCTURE", cmdBuf); sense = dev.ReadDiscInformation(out cmdBuf, out senseBuf, MmcDiscInformationDataTypes.TrackResources, dev.Timeout, out duration); if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC INFORMATION 001b\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { DicConsole.WriteLine("Track Resources Information:\n{0}", Decoders.SCSI.MMC.DiscInformation.Prettify(cmdBuf)); - doWriteFile(outputPrefix, "_readdiscinformation_001b.bin", "SCSI READ DISC INFORMATION", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscinformation_001b.bin", "SCSI READ DISC INFORMATION", cmdBuf); } sense = dev.ReadDiscInformation(out cmdBuf, out senseBuf, MmcDiscInformationDataTypes.POWResources, dev.Timeout, out duration); if(sense) @@ -882,7 +883,7 @@ namespace DiscImageChef.Commands else { DicConsole.WriteLine("POW Resources Information:\n{0}", Decoders.SCSI.MMC.DiscInformation.Prettify(cmdBuf)); - doWriteFile(outputPrefix, "_readdiscinformation_010b.bin", "SCSI READ DISC INFORMATION", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscinformation_010b.bin", "SCSI READ DISC INFORMATION", cmdBuf); } } #endregion Writable Blu-ray only @@ -905,7 +906,7 @@ namespace DiscImageChef.Commands { toc = Decoders.CD.TOC.Decode(cmdBuf); DicConsole.WriteLine("TOC:\n{0}", Decoders.CD.TOC.Prettify(toc)); - doWriteFile(outputPrefix, "_toc.bin", "SCSI READ TOC/PMA/ATIP", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_toc.bin", "SCSI READ TOC/PMA/ATIP", cmdBuf); // As we have a TOC we know it is a CD if(dskType == MediaType.Unknown) @@ -918,7 +919,7 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Media-Info command", "READ TOC/PMA/ATIP: ATIP\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(outputPrefix, "_atip.bin", "SCSI READ TOC/PMA/ATIP", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_atip.bin", "SCSI READ TOC/PMA/ATIP", cmdBuf); Decoders.CD.ATIP.CDATIP? atip = Decoders.CD.ATIP.Decode(cmdBuf); if(atip.HasValue) { @@ -940,7 +941,7 @@ namespace DiscImageChef.Commands if(discInfo.HasValue) { DicConsole.WriteLine("Standard Disc Information:\n{0}", Decoders.SCSI.MMC.DiscInformation.Prettify000b(discInfo)); - doWriteFile(outputPrefix, "_readdiscinformation_000b.bin", "SCSI READ DISC INFORMATION", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscinformation_000b.bin", "SCSI READ DISC INFORMATION", cmdBuf); // If it is a read-only CD, check CD type if available if(dskType == MediaType.CD) @@ -966,7 +967,7 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Media-Info command", "READ TOC/PMA/ATIP: Session info\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(outputPrefix, "_session.bin", "SCSI READ TOC/PMA/ATIP", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_session.bin", "SCSI READ TOC/PMA/ATIP", cmdBuf); Decoders.CD.Session.CDSessionInfo? session = Decoders.CD.Session.Decode(cmdBuf); DicConsole.WriteLine("Session information:\n{0}", Decoders.CD.Session.Prettify(session)); if(session.HasValue) @@ -1022,7 +1023,7 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Media-Info command", "READ TOC/PMA/ATIP: Raw TOC\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(outputPrefix, "_rawtoc.bin", "SCSI READ TOC/PMA/ATIP", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_rawtoc.bin", "SCSI READ TOC/PMA/ATIP", cmdBuf); DicConsole.WriteLine("Raw TOC:\n{0}", Decoders.CD.FullTOC.Prettify(cmdBuf)); } sense = dev.ReadPma(out cmdBuf, out senseBuf, dev.Timeout, out duration); @@ -1030,7 +1031,7 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Media-Info command", "READ TOC/PMA/ATIP: PMA\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(outputPrefix, "_pma.bin", "SCSI READ TOC/PMA/ATIP", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_pma.bin", "SCSI READ TOC/PMA/ATIP", cmdBuf); DicConsole.WriteLine("PMA:\n{0}", Decoders.CD.PMA.Prettify(cmdBuf)); } @@ -1039,7 +1040,7 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Media-Info command", "READ TOC/PMA/ATIP: CD-TEXT\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(outputPrefix, "_cdtext.bin", "SCSI READ TOC/PMA/ATIP", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_cdtext.bin", "SCSI READ TOC/PMA/ATIP", cmdBuf); if(Decoders.CD.CDTextOnLeadIn.Decode(cmdBuf).HasValue) DicConsole.WriteLine("CD-TEXT on Lead-In:\n{0}", Decoders.CD.CDTextOnLeadIn.Prettify(cmdBuf)); } @@ -1055,7 +1056,7 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: PFI\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(outputPrefix, "_readdiscstructure_dvd_pfi.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_pfi.bin", "SCSI READ DISC STRUCTURE", cmdBuf); Decoders.DVD.PFI.PhysicalFormatInformation? nintendoPfi = Decoders.DVD.PFI.Decode(cmdBuf); if(nintendoPfi != null) { @@ -1074,7 +1075,7 @@ namespace DiscImageChef.Commands if(sense) DicConsole.DebugWriteLine("Media-Info command", "READ DISC STRUCTURE: DMI\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_readdiscstructure_dvd_dmi.bin", "SCSI READ DISC STRUCTURE", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_dmi.bin", "SCSI READ DISC STRUCTURE", cmdBuf); } #endregion Nintendo } @@ -1096,7 +1097,7 @@ namespace DiscImageChef.Commands if(sense) DicConsole.DebugWriteLine("Media-Info command", "KREON EXTRACT SS:\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else - doWriteFile(outputPrefix, "_xbox_ss.bin", "KREON EXTRACT SS", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_xbox_ss.bin", "KREON EXTRACT SS", cmdBuf); if(Decoders.Xbox.SS.Decode(cmdBuf).HasValue) DicConsole.WriteLine("Xbox Security Sector:\n{0}", Decoders.Xbox.SS.Prettify(cmdBuf)); @@ -1198,7 +1199,7 @@ namespace DiscImageChef.Commands DicConsole.DebugWriteLine("Media-Info command", "READ MEDIA SERIAL NUMBER\n{0}", Decoders.SCSI.Sense.PrettifySense(senseBuf)); else { - doWriteFile(outputPrefix, "_mediaserialnumber.bin", "SCSI READ MEDIA SERIAL NUMBER", cmdBuf); + DataFile.WriteTo("Media-Info command", outputPrefix, "_mediaserialnumber.bin", "SCSI READ MEDIA SERIAL NUMBER", cmdBuf); if(cmdBuf.Length >= 4) { DicConsole.Write("Media Serial Number: "); @@ -1208,29 +1209,6 @@ namespace DiscImageChef.Commands } } } - - static void doWriteFile(string outputPrefix, string outputSuffix, string whatWriting, byte[] data) - { - if(!string.IsNullOrEmpty(outputPrefix)) - { - if(!File.Exists(outputPrefix + outputSuffix)) - { - try - { - DicConsole.DebugWriteLine("Media-Info command", "Writing " + whatWriting + " to {0}{1}", outputPrefix, outputSuffix); - FileStream outputFs = new FileStream(outputPrefix + outputSuffix, FileMode.CreateNew); - outputFs.Write(data, 0, data.Length); - outputFs.Close(); - } - catch - { - DicConsole.ErrorWriteLine("Unable to write file {0}{1}", outputPrefix, outputSuffix); - } - } - else - DicConsole.ErrorWriteLine("Not overwriting file {0}{1}", outputPrefix, outputSuffix); - } - } } }