Пример #1
0
        /// <summary>
        /// Generate device of type matching.
        /// </summary>
        /// <param name="devType"></param>
        /// <param name="host"></param>
        /// <param name="mac"></param>
        /// <returns></returns>
        /// <remarks>
        /// https://github.com/mjg59/python-broadlink/blob/56b2ac36e5a2359272f4af8a49cfaf3e1891733a/broadlink/__init__.py#L17-L59
        /// </remarks>
        internal static Devices.IDevice GenDevice(int devType, IPEndPoint host, byte[] mac)
        {
            var devicePair = Factory.Devices
                             .FirstOrDefault(d => d.Value.Contains(devType));

            IDevice result = null;

            if (devicePair.Equals(default(KeyValuePair <string, int[]>)))
            {
                result = new Devices.Device(host, mac, devType);
            }
            else
            {
                var assembly = Assembly.GetExecutingAssembly();

                result = (IDevice)assembly.CreateInstance(
                    $"SharpBroadlink.Devices.{devicePair.Key}", // Full class name
                    false,
                    BindingFlags.CreateInstance,
                    null,
                    new object[] { host, mac, devType }, // passing values for constructor
                    null,
                    null);
            }

            return(result);
        }
Пример #2
0
        static string DeviceConnectionString(string ioTHubHostName, Devices.Device device)
        {
            string deviceConnectionString = string.Format("HostName={0};CredentialScope=Device;DeviceId={1};SharedAccessKey={2}",
                                                          ioTHubHostName,
                                                          device.Id,
                                                          device.Authentication.SymmetricKey.PrimaryKey);

            return(deviceConnectionString);
        }
Пример #3
0
        public void Add(Devices.Device aDevice)
        {
            mAll.Add(aDevice);

            if (aDevice is Processor)
            {
                mProcessor = (Processor)aDevice;
            }
        }
Пример #4
0
        public bool RenameProject(Project prj, string newName)
        {
            string newDir     = System.IO.Path.Combine(MainClass.Workspace.RootDirectory, newName);
            string newApp     = System.IO.Path.Combine(MainClass.Workspace.RootDirectory, newName + ".app");
            string newPrj     = System.IO.Path.Combine(MainClass.Workspace.RootDirectory, newName + ".msp");
            string oldPrjName = prj.ProjectName;

            if (File.Exists(newApp) || File.Exists(newPrj) || Directory.Exists(newDir))
            {
                MessageDialogs md =
                    new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("cannot_rename_project", prj.ProjectName), MainClass.Languages.Translate("project_exist"), Gtk.MessageType.Error);
                md.ShowDialog();
                return(false);
            }

            string oldPrjFile = prj.FilePath;

            System.IO.File.Move(prj.AbsolutAppFilePath, newApp);
            System.IO.File.Move(prj.FilePath, newPrj);
            System.IO.Directory.Move(prj.AbsolutProjectDir, newDir);

            prj.AppFilePath = GetRelativePath(newApp);
            prj.FilePath    = newPrj;

            foreach (FileItem fi in prj.FilesProperty)
            {
                fi.FilePath = fi.FilePath.Replace("./" + oldPrjName + "/", "./" + newName + "/");
                fi.FilePath = fi.FilePath.Replace(".\\" + oldPrjName + "\\", ".\\" + newName + "\\");
                //MainClass.Workspace.GetRelativePath(d.FullName);
            }

            SaveProject(prj);

            ProjectsFile.Remove(GetRelativePath(oldPrjFile));
            ProjectsFile.Add(GetRelativePath(prj.FilePath));

            Devices.Device dev = prj.DevicesSettings.Find(x => x.Devicetype == DeviceType.iOS_5_0);
            if (dev != null)
            {
                Devices.PublishProperty pp = dev.PublishPropertisMask.Find(x => x.PublishName == Project.KEY_BUNDLEIDENTIFIER);
                if (pp != null)
                {
                    pp.PublishValue.Replace(oldPrjName, newName);
                }
            }
            return(true);
        }
Пример #5
0
        public static int Invoke(bool debug, bool verbose, string cicmXml, string devicePath, bool resume,
                                 string encoding, bool firstPregap, bool fixOffset, bool force, bool metadata,
                                 bool trim, string outputPath, string options, bool persistent, ushort retryPasses,
                                 uint skip, byte speed, bool stopOnError, string format, string subchannel,
                                 bool @private, bool fixSubchannelPosition, bool retrySubchannel, bool fixSubchannel,
                                 bool fixSubchannelCrc, bool generateSubchannels, bool skipCdiReadyHole, bool eject)
        {
            MainClass.PrintCopyright();

            if (debug)
            {
                AaruConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
            }

            if (verbose)
            {
                AaruConsole.VerboseWriteLineEvent += System.Console.WriteLine;
            }

            if (fixSubchannelCrc)
            {
                fixSubchannel = true;
            }

            if (retrySubchannel || fixSubchannel)
            {
                fixSubchannelPosition = true;
            }

            Statistics.AddCommand("dump-media");

            AaruConsole.DebugWriteLine("Dump-Media command", "--cicm-xml={0}", cicmXml);
            AaruConsole.DebugWriteLine("Dump-Media command", "--debug={0}", debug);
            AaruConsole.DebugWriteLine("Dump-Media command", "--device={0}", devicePath);
            AaruConsole.DebugWriteLine("Dump-Media command", "--encoding={0}", encoding);
            AaruConsole.DebugWriteLine("Dump-Media command", "--first-pregap={0}", firstPregap);
            AaruConsole.DebugWriteLine("Dump-Media command", "--fix-offset={0}", fixOffset);
            AaruConsole.DebugWriteLine("Dump-Media command", "--force={0}", force);
            AaruConsole.DebugWriteLine("Dump-Media command", "--format={0}", format);
            AaruConsole.DebugWriteLine("Dump-Media command", "--metadata={0}", metadata);
            AaruConsole.DebugWriteLine("Dump-Media command", "--options={0}", options);
            AaruConsole.DebugWriteLine("Dump-Media command", "--output={0}", outputPath);
            AaruConsole.DebugWriteLine("Dump-Media command", "--persistent={0}", persistent);
            AaruConsole.DebugWriteLine("Dump-Media command", "--resume={0}", resume);
            AaruConsole.DebugWriteLine("Dump-Media command", "--retry-passes={0}", retryPasses);
            AaruConsole.DebugWriteLine("Dump-Media command", "--skip={0}", skip);
            AaruConsole.DebugWriteLine("Dump-Media command", "--stop-on-error={0}", stopOnError);
            AaruConsole.DebugWriteLine("Dump-Media command", "--trim={0}", trim);
            AaruConsole.DebugWriteLine("Dump-Media command", "--verbose={0}", verbose);
            AaruConsole.DebugWriteLine("Dump-Media command", "--subchannel={0}", subchannel);
            AaruConsole.DebugWriteLine("Dump-Media command", "--private={0}", @private);
            AaruConsole.DebugWriteLine("Dump-Media command", "--fix-subchannel-position={0}", fixSubchannelPosition);
            AaruConsole.DebugWriteLine("Dump-Media command", "--retry-subchannel={0}", retrySubchannel);
            AaruConsole.DebugWriteLine("Dump-Media command", "--fix-subchannel={0}", fixSubchannel);
            AaruConsole.DebugWriteLine("Dump-Media command", "--fix-subchannel-crc={0}", fixSubchannelCrc);
            AaruConsole.DebugWriteLine("Dump-Media command", "--generate-subchannels={0}", generateSubchannels);
            AaruConsole.DebugWriteLine("Dump-Media command", "--skip-cdiready-hole={0}", skipCdiReadyHole);
            AaruConsole.DebugWriteLine("Dump-Media command", "--eject={0}", eject);

            // TODO: Disabled temporarily
            //AaruConsole.DebugWriteLine("Dump-Media command", "--raw={0}",           raw);

            Dictionary <string, string> parsedOptions = Core.Options.Parse(options);

            AaruConsole.DebugWriteLine("Dump-Media command", "Parsed options:");

            foreach (KeyValuePair <string, string> parsedOption in parsedOptions)
            {
                AaruConsole.DebugWriteLine("Dump-Media command", "{0} = {1}", parsedOption.Key, parsedOption.Value);
            }

            Encoding encodingClass = null;

            if (encoding != null)
            {
                try
                {
                    encodingClass = Claunia.Encoding.Encoding.GetEncoding(encoding);

                    if (verbose)
                    {
                        AaruConsole.VerboseWriteLine("Using encoding for {0}.", encodingClass.EncodingName);
                    }
                }
                catch (ArgumentException)
                {
                    AaruConsole.ErrorWriteLine("Specified encoding is not supported.");

                    return((int)ErrorNumber.EncodingUnknown);
                }
            }

            DumpSubchannel wantedSubchannel = DumpSubchannel.Any;

            switch (subchannel?.ToLowerInvariant())
            {
            case "any":
            case null:
                wantedSubchannel = DumpSubchannel.Any;

                break;

            case "rw":
                wantedSubchannel = DumpSubchannel.Rw;

                break;

            case "rw-or-pq":
                wantedSubchannel = DumpSubchannel.RwOrPq;

                break;

            case "pq":
                wantedSubchannel = DumpSubchannel.Pq;

                break;

            case "none":
                wantedSubchannel = DumpSubchannel.None;

                break;

            default:
                AaruConsole.WriteLine("Incorrect subchannel type \"{0}\" requested.", subchannel);

                break;
            }

            string filename = Path.GetFileNameWithoutExtension(outputPath);

            bool isResponse = filename.StartsWith("#", StringComparison.OrdinalIgnoreCase) &&
                              File.Exists(Path.Combine(Path.GetDirectoryName(outputPath),
                                                       Path.GetFileNameWithoutExtension(outputPath)));

            TextReader resReader;

            if (isResponse)
            {
                resReader = new StreamReader(Path.Combine(Path.GetDirectoryName(outputPath),
                                                          Path.GetFileNameWithoutExtension(outputPath)));
            }
            else
            {
                resReader = new StringReader(Path.GetFileNameWithoutExtension(outputPath));
            }

            if (isResponse)
            {
                eject = true;
            }

            PluginBase            plugins    = GetPluginBase.Instance;
            List <IWritableImage> candidates = new List <IWritableImage>();
            string extension = Path.GetExtension(outputPath);

            // Try extension
            if (string.IsNullOrEmpty(format))
            {
                candidates.AddRange(plugins.WritableImages.Values.Where(t => t.KnownExtensions.Contains(extension)));
            }

            // Try Id
            else if (Guid.TryParse(format, out Guid outId))
            {
                candidates.AddRange(plugins.WritableImages.Values.Where(t => t.Id.Equals(outId)));
            }

            // Try name
            else
            {
                candidates.AddRange(plugins.WritableImages.Values.Where(t => string.Equals(t.Name, format,
                                                                                           StringComparison.
                                                                                           InvariantCultureIgnoreCase)));
            }

            if (candidates.Count == 0)
            {
                AaruConsole.WriteLine("No plugin supports requested extension.");

                return((int)ErrorNumber.FormatNotFound);
            }

            if (candidates.Count > 1)
            {
                AaruConsole.WriteLine("More than one plugin supports requested extension.");

                return((int)ErrorNumber.TooManyFormats);
            }

            while (true)
            {
                string responseLine = resReader.ReadLine();

                if (responseLine is null)
                {
                    break;
                }

                if (responseLine.Any(c => c < 0x20))
                {
                    AaruConsole.ErrorWriteLine("Invalid characters found in list of files, exiting...");

                    return((int)ErrorNumber.InvalidArgument);
                }

                if (isResponse)
                {
                    AaruConsole.WriteLine("Please insert media with title {0} and press any key to continue...",
                                          responseLine);

                    System.Console.ReadKey();
                    Thread.Sleep(1000);
                }

                responseLine = responseLine.Replace('/', '/');

                // Replace Windows forbidden filename characters with Japanese equivalents that are visually the same, but bigger.
                if (DetectOS.IsWindows)
                {
                    responseLine = responseLine.Replace('<', '\uFF1C').Replace('>', '\uFF1E').Replace(':', '\uFF1A').
                                   Replace('"', '\u2033').Replace('\\', '\').Replace('|', '|').
                                   Replace('?', '?').Replace('*', '*');
                }

                if (devicePath.Length == 2 &&
                    devicePath[1] == ':' &&
                    devicePath[0] != '/' &&
                    char.IsLetter(devicePath[0]))
                {
                    devicePath = "\\\\.\\" + char.ToUpper(devicePath[0]) + ':';
                }

                Devices.Device dev;

                try
                {
                    dev = new Devices.Device(devicePath);

                    if (dev.IsRemote)
                    {
                        Statistics.AddRemote(dev.RemoteApplication, dev.RemoteVersion, dev.RemoteOperatingSystem,
                                             dev.RemoteOperatingSystemVersion, dev.RemoteArchitecture);
                    }

                    if (dev.Error)
                    {
                        AaruConsole.ErrorWriteLine(Error.Print(dev.LastError));

                        if (isResponse)
                        {
                            continue;
                        }

                        return((int)ErrorNumber.CannotOpenDevice);
                    }
                }
                catch (DeviceException e)
                {
                    AaruConsole.ErrorWriteLine(e.Message ?? Error.Print(e.LastError));

                    if (isResponse)
                    {
                        continue;
                    }

                    return((int)ErrorNumber.CannotOpenDevice);
                }

                Statistics.AddDevice(dev);

                string outputPrefix = Path.Combine(Path.GetDirectoryName(outputPath), responseLine);

                Resume resumeClass = null;
                var    xs          = new XmlSerializer(typeof(Resume));

                if (File.Exists(outputPrefix + ".resume.xml") && resume)
                {
                    try
                    {
                        var sr = new StreamReader(outputPrefix + ".resume.xml");
                        resumeClass = (Resume)xs.Deserialize(sr);
                        sr.Close();
                    }
                    catch
                    {
                        AaruConsole.ErrorWriteLine("Incorrect resume file, not continuing...");

                        if (isResponse)
                        {
                            continue;
                        }

                        return((int)ErrorNumber.InvalidResume);
                    }
                }

                if (resumeClass != null &&
                    resumeClass.NextBlock > resumeClass.LastBlock &&
                    resumeClass.BadBlocks.Count == 0 &&
                    !resumeClass.Tape &&
                    (resumeClass.BadSubchannels is null || resumeClass.BadSubchannels.Count == 0))
                {
                    AaruConsole.WriteLine("Media already dumped correctly, not continuing...");

                    if (isResponse)
                    {
                        continue;
                    }

                    return((int)ErrorNumber.AlreadyDumped);
                }

                CICMMetadataType sidecar = null;
                var sidecarXs            = new XmlSerializer(typeof(CICMMetadataType));

                if (cicmXml != null)
                {
                    if (File.Exists(cicmXml))
                    {
                        try
                        {
                            var sr = new StreamReader(cicmXml);
                            sidecar = (CICMMetadataType)sidecarXs.Deserialize(sr);
                            sr.Close();
                        }
                        catch
                        {
                            AaruConsole.ErrorWriteLine("Incorrect metadata sidecar file, not continuing...");

                            if (isResponse)
                            {
                                continue;
                            }

                            return((int)ErrorNumber.InvalidSidecar);
                        }
                    }
                    else
                    {
                        AaruConsole.ErrorWriteLine("Could not find metadata sidecar, not continuing...");

                        if (isResponse)
                        {
                            continue;
                        }

                        return((int)ErrorNumber.FileNotFound);
                    }
                }

                plugins    = GetPluginBase.Instance;
                candidates = new List <IWritableImage>();

                // Try extension
                if (string.IsNullOrEmpty(format))
                {
                    candidates.AddRange(plugins.WritableImages.Values.Where(t =>
                                                                            t.KnownExtensions.
                                                                            Contains(Path.
                                                                                     GetExtension(outputPath))));
                }

                // Try Id
                else if (Guid.TryParse(format, out Guid outId))
                {
                    candidates.AddRange(plugins.WritableImages.Values.Where(t => t.Id.Equals(outId)));
                }

                // Try name
                else
                {
                    candidates.AddRange(plugins.WritableImages.Values.Where(t => string.Equals(t.Name, format,
                                                                                               StringComparison.
                                                                                               InvariantCultureIgnoreCase)));
                }

                IWritableImage outputFormat = candidates[0];

                var dumpLog = new DumpLog(outputPrefix + ".log", dev, @private);

                if (verbose)
                {
                    dumpLog.WriteLine("Output image format: {0} ({1}).", outputFormat.Name, outputFormat.Id);
                    AaruConsole.VerboseWriteLine("Output image format: {0} ({1}).", outputFormat.Name, outputFormat.Id);
                }
                else
                {
                    dumpLog.WriteLine("Output image format: {0}.", outputFormat.Name);
                    AaruConsole.WriteLine("Output image format: {0}.", outputFormat.Name);
                }

                var errorLog = new ErrorLog(outputPrefix + ".error.log");

                var dumper = new Dump(resume, dev, devicePath, outputFormat, retryPasses, force, false, persistent,
                                      stopOnError, resumeClass, dumpLog, encodingClass, outputPrefix,
                                      outputPrefix + extension, parsedOptions, sidecar, skip, metadata, trim,
                                      firstPregap, fixOffset, debug, wantedSubchannel, speed, @private,
                                      fixSubchannelPosition, retrySubchannel, fixSubchannel, fixSubchannelCrc,
                                      skipCdiReadyHole, errorLog, generateSubchannels);

                dumper.UpdateStatus         += Progress.UpdateStatus;
                dumper.ErrorMessage         += Progress.ErrorMessage;
                dumper.StoppingErrorMessage += Progress.ErrorMessage;
                dumper.UpdateProgress       += Progress.UpdateProgress;
                dumper.PulseProgress        += Progress.PulseProgress;
                dumper.InitProgress         += Progress.InitProgress;
                dumper.EndProgress          += Progress.EndProgress;
                dumper.InitProgress2        += Progress.InitProgress2;
                dumper.EndProgress2         += Progress.EndProgress2;
                dumper.UpdateProgress2      += Progress.UpdateProgress2;

                System.Console.CancelKeyPress += (sender, e) =>
                {
                    e.Cancel = true;
                    dumper.Abort();
                };

                dumper.Start();

                if (eject && dev.IsRemovable)
                {
                    switch (dev.Type)
                    {
                    case DeviceType.ATA:
                        dev.DoorUnlock(out _, dev.Timeout, out _);
                        dev.MediaEject(out _, dev.Timeout, out _);

                        break;

                    case DeviceType.ATAPI:
                    case DeviceType.SCSI:
                        switch (dev.ScsiType)
                        {
                        case PeripheralDeviceTypes.DirectAccess:
                        case PeripheralDeviceTypes.SimplifiedDevice:
                        case PeripheralDeviceTypes.SCSIZonedBlockDevice:
                        case PeripheralDeviceTypes.WriteOnceDevice:
                        case PeripheralDeviceTypes.OpticalDevice:
                        case PeripheralDeviceTypes.OCRWDevice:
                            dev.SpcAllowMediumRemoval(out _, dev.Timeout, out _);
                            dev.EjectTray(out _, dev.Timeout, out _);

                            break;

                        case PeripheralDeviceTypes.MultiMediaDevice:
                            dev.AllowMediumRemoval(out _, dev.Timeout, out _);
                            dev.EjectTray(out _, dev.Timeout, out _);

                            break;

                        case PeripheralDeviceTypes.SequentialAccess:
                            dev.SpcAllowMediumRemoval(out _, dev.Timeout, out _);
                            dev.LoadUnload(out _, true, false, false, false, false, dev.Timeout, out _);

                            break;
                        }

                        break;
                    }
                }

                dev.Close();
            }

            return((int)ErrorNumber.NoError);
        }
Пример #6
0
        public static int Invoke(bool debug, bool verbose, string devicePath, string outputPrefix)
        {
            MainClass.PrintCopyright();

            if (debug)
            {
                AaruConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
            }

            if (verbose)
            {
                AaruConsole.VerboseWriteLineEvent += System.Console.WriteLine;
            }

            Statistics.AddCommand("media-info");

            AaruConsole.DebugWriteLine("Media-Info command", "--debug={0}", debug);
            AaruConsole.DebugWriteLine("Media-Info command", "--device={0}", devicePath);
            AaruConsole.DebugWriteLine("Media-Info command", "--output-prefix={0}", outputPrefix);
            AaruConsole.DebugWriteLine("Media-Info command", "--verbose={0}", verbose);

            if (devicePath.Length == 2 &&
                devicePath[1] == ':' &&
                devicePath[0] != '/' &&
                char.IsLetter(devicePath[0]))
            {
                devicePath = "\\\\.\\" + char.ToUpper(devicePath[0]) + ':';
            }

            Devices.Device dev;

            try
            {
                dev = new Devices.Device(devicePath);

                if (dev.IsRemote)
                {
                    Statistics.AddRemote(dev.RemoteApplication, dev.RemoteVersion, dev.RemoteOperatingSystem,
                                         dev.RemoteOperatingSystemVersion, dev.RemoteArchitecture);
                }

                if (dev.Error)
                {
                    AaruConsole.ErrorWriteLine(Error.Print(dev.LastError));

                    return((int)ErrorNumber.CannotOpenDevice);
                }
            }
            catch (DeviceException e)
            {
                AaruConsole.ErrorWriteLine(e.Message ?? Error.Print(e.LastError));

                return((int)ErrorNumber.CannotOpenDevice);
            }

            Statistics.AddDevice(dev);

            switch (dev.Type)
            {
            case DeviceType.ATA:
                DoAtaMediaInfo();

                break;

            case DeviceType.MMC:
            case DeviceType.SecureDigital:
                DoSdMediaInfo();

                break;

            case DeviceType.NVMe:
                DoNvmeMediaInfo(outputPrefix, dev);

                break;

            case DeviceType.ATAPI:
            case DeviceType.SCSI:
                DoScsiMediaInfo(debug, verbose, outputPrefix, dev);

                break;

            default: throw new NotSupportedException("Unknown device type.");
            }

            return((int)ErrorNumber.NoError);
        }
Пример #7
0
        static void DoScsiMediaInfo(bool debug, bool verbose, string outputPrefix, Devices.Device dev)
        {
            var scsiInfo = new ScsiInfo(dev);

            if (!scsiInfo.MediaInserted)
            {
                return;
            }

            if (scsiInfo.DeviceInfo.ScsiModeSense6 != null)
            {
                DataFile.WriteTo("Media-Info command", outputPrefix, "_scsi_modesense6.bin", "SCSI MODE SENSE (6)",
                                 scsiInfo.DeviceInfo.ScsiModeSense6);
            }

            if (scsiInfo.DeviceInfo.ScsiModeSense10 != null)
            {
                DataFile.WriteTo("Media-Info command", outputPrefix, "_scsi_modesense10.bin", "SCSI MODE SENSE (10)",
                                 scsiInfo.DeviceInfo.ScsiModeSense10);
            }

            switch (dev.ScsiType)
            {
            case PeripheralDeviceTypes.DirectAccess:
            case PeripheralDeviceTypes.MultiMediaDevice:
            case PeripheralDeviceTypes.OCRWDevice:
            case PeripheralDeviceTypes.OpticalDevice:
            case PeripheralDeviceTypes.SimplifiedDevice:
            case PeripheralDeviceTypes.WriteOnceDevice:
                if (scsiInfo.ReadCapacity != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readcapacity.bin", "SCSI READ CAPACITY",
                                     scsiInfo.ReadCapacity);
                }

                if (scsiInfo.ReadCapacity16 != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readcapacity16.bin",
                                     "SCSI READ CAPACITY(16)", scsiInfo.ReadCapacity16);
                }

                if (scsiInfo.Blocks != 0 &&
                    scsiInfo.BlockSize != 0)
                {
                    AaruConsole.WriteLine("Media has {0} blocks of {1} bytes/each. (for a total of {2} bytes)",
                                          scsiInfo.Blocks, scsiInfo.BlockSize,
                                          scsiInfo.Blocks * scsiInfo.BlockSize);
                }

                break;

            case PeripheralDeviceTypes.SequentialAccess:
                if (scsiInfo.DensitySupport != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_ssc_reportdensitysupport_media.bin",
                                     "SSC REPORT DENSITY SUPPORT (MEDIA)", scsiInfo.DensitySupport);

                    if (scsiInfo.DensitySupportHeader.HasValue)
                    {
                        AaruConsole.WriteLine("Densities supported by currently inserted media:");
                        AaruConsole.WriteLine(DensitySupport.PrettifyDensity(scsiInfo.DensitySupportHeader));
                    }
                }

                if (scsiInfo.MediaTypeSupport != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix,
                                     "_ssc_reportdensitysupport_medium_media.bin",
                                     "SSC REPORT DENSITY SUPPORT (MEDIUM & MEDIA)", scsiInfo.MediaTypeSupport);

                    if (scsiInfo.MediaTypeSupportHeader.HasValue)
                    {
                        AaruConsole.WriteLine("Medium types currently inserted in device:");
                        AaruConsole.WriteLine(DensitySupport.PrettifyMediumType(scsiInfo.MediaTypeSupportHeader));
                    }

                    AaruConsole.WriteLine(DensitySupport.PrettifyMediumType(scsiInfo.MediaTypeSupport));
                }

                break;
            }

            if (dev.ScsiType == PeripheralDeviceTypes.MultiMediaDevice)
            {
                if (scsiInfo.MmcConfiguration != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_getconfiguration_current.bin",
                                     "SCSI GET CONFIGURATION", scsiInfo.MmcConfiguration);
                }

                if (scsiInfo.RecognizedFormatLayers != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_formatlayers.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.RecognizedFormatLayers);
                }

                if (scsiInfo.WriteProtectionStatus != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_writeprotection.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.WriteProtectionStatus);
                }

                if (scsiInfo.DvdPfi != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_pfi.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdPfi);

                    if (scsiInfo.DecodedPfi.HasValue)
                    {
                        AaruConsole.WriteLine("PFI:\n{0}", PFI.Prettify(scsiInfo.DecodedPfi));
                    }
                }

                if (scsiInfo.DvdDmi != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_dmi.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdDmi);

                    if (DMI.IsXbox(scsiInfo.DvdDmi))
                    {
                        AaruConsole.WriteLine("Xbox DMI:\n{0}", DMI.PrettifyXbox(scsiInfo.DvdDmi));
                    }
                    else if (DMI.IsXbox360(scsiInfo.DvdDmi))
                    {
                        AaruConsole.WriteLine("Xbox 360 DMI:\n{0}", DMI.PrettifyXbox360(scsiInfo.DvdDmi));
                    }
                }

                if (scsiInfo.DvdCmi != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_cmi.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdCmi);

                    AaruConsole.WriteLine("Lead-In CMI:\n{0}", CSS_CPRM.PrettifyLeadInCopyright(scsiInfo.DvdCmi));
                }

                if (scsiInfo.DvdBca != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_bca.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdBca);
                }

                if (scsiInfo.DvdAacs != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_aacs.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdAacs);
                }

                if (scsiInfo.DvdRamDds != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdram_dds.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdRamDds);

                    AaruConsole.WriteLine("Disc Definition Structure:\n{0}", DDS.Prettify(scsiInfo.DvdRamDds));
                }

                if (scsiInfo.DvdRamCartridgeStatus != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdram_status.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdRamCartridgeStatus);

                    AaruConsole.WriteLine("Medium Status:\n{0}", Cartridge.Prettify(scsiInfo.DvdRamCartridgeStatus));
                }

                if (scsiInfo.DvdRamSpareArea != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdram_spare.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdRamSpareArea);

                    AaruConsole.WriteLine("Spare Area Information:\n{0}", Spare.Prettify(scsiInfo.DvdRamSpareArea));
                }

                if (scsiInfo.LastBorderOutRmd != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_lastrmd.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.LastBorderOutRmd);
                }

                if (scsiInfo.DvdPreRecordedInfo != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_pri.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdPreRecordedInfo);
                }

                if (scsiInfo.DvdrMediaIdentifier != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdr_mediaid.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdrMediaIdentifier);
                }

                if (scsiInfo.DvdrPhysicalInformation != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdr_pfi.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdrPhysicalInformation);
                }

                if (scsiInfo.DvdPlusAdip != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd+_adip.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdPlusAdip);
                }

                if (scsiInfo.DvdPlusDcb != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd+_dcb.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdPlusDcb);
                }

                if (scsiInfo.HddvdCopyrightInformation != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_hddvd_cmi.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.HddvdCopyrightInformation);
                }

                if (scsiInfo.HddvdrMediumStatus != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_hddvdr_status.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.HddvdrMediumStatus);
                }

                if (scsiInfo.HddvdrLastRmd != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_hddvdr_lastrmd.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.HddvdrLastRmd);
                }

                if (scsiInfo.DvdrLayerCapacity != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdr_layercap.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdrLayerCapacity);
                }

                if (scsiInfo.DvdrDlMiddleZoneStart != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_mzs.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdrDlMiddleZoneStart);
                }

                if (scsiInfo.DvdrDlJumpIntervalSize != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_jis.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdrDlJumpIntervalSize);
                }

                if (scsiInfo.DvdrDlManualLayerJumpStartLba != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_manuallj.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdrDlManualLayerJumpStartLba);
                }

                if (scsiInfo.DvdrDlRemapAnchorPoint != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_remapanchor.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdrDlRemapAnchorPoint);
                }

                if (scsiInfo.BlurayDiscInformation != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_di.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.BlurayDiscInformation);

                    AaruConsole.WriteLine("Blu-ray Disc Information:\n{0}",
                                          DI.Prettify(scsiInfo.BlurayDiscInformation));
                }

                if (scsiInfo.BlurayPac != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_pac.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.BlurayPac);
                }

                if (scsiInfo.BlurayBurstCuttingArea != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_bca.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.BlurayBurstCuttingArea);

                    AaruConsole.WriteLine("Blu-ray Burst Cutting Area:\n{0}",
                                          BCA.Prettify(scsiInfo.BlurayBurstCuttingArea));
                }

                if (scsiInfo.BlurayDds != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_dds.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.BlurayDds);

                    AaruConsole.WriteLine("Blu-ray Disc Definition Structure:\n{0}",
                                          Decoders.Bluray.DDS.Prettify(scsiInfo.BlurayDds));
                }

                if (scsiInfo.BlurayCartridgeStatus != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_cartstatus.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.BlurayCartridgeStatus);

                    AaruConsole.WriteLine("Blu-ray Cartridge Status:\n{0}",
                                          Decoders.Bluray.Cartridge.Prettify(scsiInfo.BlurayCartridgeStatus));
                }

                if (scsiInfo.BluraySpareAreaInformation != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_spare.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.BluraySpareAreaInformation);

                    AaruConsole.WriteLine("Blu-ray Spare Area Information:\n{0}",
                                          Decoders.Bluray.Spare.Prettify(scsiInfo.BluraySpareAreaInformation));
                }

                if (scsiInfo.BlurayRawDfl != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_dfl.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.BlurayRawDfl);
                }

                if (scsiInfo.BlurayTrackResources != null)
                {
                    AaruConsole.WriteLine("Track Resources Information:\n{0}",
                                          DiscInformation.Prettify(scsiInfo.BlurayTrackResources));

                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscinformation_001b.bin",
                                     "SCSI READ DISC INFORMATION", scsiInfo.BlurayTrackResources);
                }

                if (scsiInfo.BlurayPowResources != null)
                {
                    AaruConsole.WriteLine("POW Resources Information:\n{0}",
                                          DiscInformation.Prettify(scsiInfo.BlurayPowResources));

                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscinformation_010b.bin",
                                     "SCSI READ DISC INFORMATION", scsiInfo.BlurayPowResources);
                }

                if (scsiInfo.Toc != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_toc.bin", "SCSI READ TOC/PMA/ATIP",
                                     scsiInfo.Toc);

                    if (scsiInfo.DecodedToc.HasValue)
                    {
                        AaruConsole.WriteLine("TOC:\n{0}", TOC.Prettify(scsiInfo.DecodedToc));
                    }
                }

                if (scsiInfo.Atip != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_atip.bin", "SCSI READ TOC/PMA/ATIP",
                                     scsiInfo.Atip);

                    if (scsiInfo.DecodedAtip.HasValue)
                    {
                        AaruConsole.WriteLine("ATIP:\n{0}", ATIP.Prettify(scsiInfo.DecodedAtip));
                    }
                }

                if (scsiInfo.CompactDiscInformation != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscinformation_000b.bin",
                                     "SCSI READ DISC INFORMATION", scsiInfo.CompactDiscInformation);

                    if (scsiInfo.DecodedCompactDiscInformation.HasValue)
                    {
                        AaruConsole.WriteLine("Standard Disc Information:\n{0}",
                                              DiscInformation.Prettify000b(scsiInfo.DecodedCompactDiscInformation));
                    }
                }

                if (scsiInfo.Session != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_session.bin", "SCSI READ TOC/PMA/ATIP",
                                     scsiInfo.Session);

                    if (scsiInfo.DecodedSession.HasValue)
                    {
                        AaruConsole.WriteLine("Session information:\n{0}", Session.Prettify(scsiInfo.DecodedSession));
                    }
                }

                if (scsiInfo.RawToc != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_rawtoc.bin", "SCSI READ TOC/PMA/ATIP",
                                     scsiInfo.RawToc);

                    if (scsiInfo.FullToc.HasValue)
                    {
                        AaruConsole.WriteLine("Raw TOC:\n{0}", FullTOC.Prettify(scsiInfo.RawToc));
                    }
                }

                if (scsiInfo.Pma != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_pma.bin", "SCSI READ TOC/PMA/ATIP",
                                     scsiInfo.Pma);

                    AaruConsole.WriteLine("PMA:\n{0}", PMA.Prettify(scsiInfo.Pma));
                }

                if (scsiInfo.CdTextLeadIn != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_cdtext.bin", "SCSI READ TOC/PMA/ATIP",
                                     scsiInfo.CdTextLeadIn);

                    if (scsiInfo.DecodedCdTextLeadIn.HasValue)
                    {
                        AaruConsole.WriteLine("CD-TEXT on Lead-In:\n{0}",
                                              CDTextOnLeadIn.Prettify(scsiInfo.DecodedCdTextLeadIn));
                    }
                }

                if (!string.IsNullOrEmpty(scsiInfo.Mcn))
                {
                    AaruConsole.WriteLine("MCN: {0}", scsiInfo.Mcn);
                }

                if (scsiInfo.Isrcs != null)
                {
                    foreach (KeyValuePair <byte, string> isrc in scsiInfo.Isrcs)
                    {
                        AaruConsole.WriteLine("Track's {0} ISRC: {1}", isrc.Key, isrc.Value);
                    }
                }

                if (scsiInfo.XboxSecuritySector != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_xbox_ss.bin", "KREON EXTRACT SS",
                                     scsiInfo.XboxSecuritySector);
                }

                if (scsiInfo.DecodedXboxSecuritySector.HasValue)
                {
                    AaruConsole.WriteLine("Xbox Security Sector:\n{0}",
                                          SS.Prettify(scsiInfo.DecodedXboxSecuritySector));
                }

                if (scsiInfo.XgdInfo != null)
                {
                    AaruConsole.WriteLine("Video layer 0 size: {0} sectors", scsiInfo.XgdInfo.L0Video);
                    AaruConsole.WriteLine("Video layer 1 size: {0} sectors", scsiInfo.XgdInfo.L1Video);
                    AaruConsole.WriteLine("Middle zone size: {0} sectors", scsiInfo.XgdInfo.MiddleZone);
                    AaruConsole.WriteLine("Game data size: {0} sectors", scsiInfo.XgdInfo.GameSize);
                    AaruConsole.WriteLine("Total size: {0} sectors", scsiInfo.XgdInfo.TotalSize);
                    AaruConsole.WriteLine("Real layer break: {0}", scsiInfo.XgdInfo.LayerBreak);
                    AaruConsole.WriteLine();
                }
            }

            if (scsiInfo.MediaSerialNumber != null)
            {
                DataFile.WriteTo("Media-Info command", outputPrefix, "_mediaserialnumber.bin",
                                 "SCSI READ MEDIA SERIAL NUMBER", scsiInfo.MediaSerialNumber);

                AaruConsole.Write("Media Serial Number: ");

                for (int i = 4; i < scsiInfo.MediaSerialNumber.Length; i++)
                {
                    AaruConsole.Write("{0:X2}", scsiInfo.MediaSerialNumber[i]);
                }

                AaruConsole.WriteLine();
            }

            AaruConsole.WriteLine("Media identified as {0}", scsiInfo.MediaType);
            Statistics.AddMedia(scsiInfo.MediaType, true);

            if (scsiInfo.Toc != null ||
                scsiInfo.RawToc != null)
            {
                uint blockSize = 2352;

                Track[] tracks = Dump.GetCdTracks(ref blockSize, dev, scsiInfo.MediaType, null, false,
                                                  out long lastSector, null, null, null, TrackSubchannelType.None,
                                                  out _, null, null);

                if (tracks != null)
                {
                    bool supportsPqSubchannel = Dump.SupportsPqSubchannel(dev, null, null);
                    bool supportsRwSubchannel = Dump.SupportsRwSubchannel(dev, null, null);

                    // Open master database
                    var ctx = AaruContext.Create(Settings.Settings.MasterDbPath);

                    // Search for device in master database
                    Database.Models.Device dbDev =
                        ctx.Devices.FirstOrDefault(d => d.Manufacturer == dev.Manufacturer && d.Model == dev.Model &&
                                                   d.Revision == dev.FirmwareRevision);

                    Dump.SolveTrackPregaps(dev, null, null, tracks, supportsPqSubchannel, supportsRwSubchannel, dbDev,
                                           out bool inexactPositioning);

                    for (int t = 1; t < tracks.Length; t++)
                    {
                        tracks[t - 1].TrackEndSector = tracks[t].TrackStartSector - 1;
                    }

                    tracks[tracks.Length - 1].TrackEndSector = (ulong)lastSector;

                    AaruConsole.WriteLine();
                    AaruConsole.WriteLine("Track calculations:");

                    if (inexactPositioning)
                    {
                        AaruConsole.
                        WriteLine("WARNING: The drive has returned incorrect Q positioning when calculating pregaps. A best effort has been tried but they may be incorrect.");
                    }

                    foreach (Track track in tracks)
                    {
                        AaruConsole.
                        WriteLine("Track {0} starts at LBA {1}, ends at LBA {2}, has a pregap of {3} sectors and is of type {4}",
                                  track.TrackSequence, track.TrackStartSector, track.TrackEndSector,
                                  track.TrackPregap, track.TrackType);
                    }

                    AaruConsole.WriteLine();
                    AaruConsole.WriteLine("Offsets:");

                    CdOffset cdOffset = null;

                    // Search for read offset in master database
                    cdOffset = ctx.CdOffsets.FirstOrDefault(d => d.Manufacturer == dev.Manufacturer &&
                                                            d.Model == dev.Model);

                    CompactDisc.GetOffset(cdOffset, dbDev, debug, dev, scsiInfo.MediaType, null, tracks, null,
                                          out int?driveOffset, out int?combinedOffset, out _);

                    if (combinedOffset is null)
                    {
                        if (driveOffset is null)
                        {
                            AaruConsole.WriteLine("Drive reading offset not found in database.");
                            AaruConsole.WriteLine("Disc offset cannot be calculated.");
                        }
                        else
                        {
                            AaruConsole.
                            WriteLine($"Drive reading offset is {driveOffset} bytes ({driveOffset / 4} samples).");

                            AaruConsole.WriteLine("Disc write offset is unknown.");
                        }
                    }
                    else
                    {
                        int offsetBytes = combinedOffset.Value;

                        if (driveOffset is null)
                        {
                            AaruConsole.WriteLine("Drive reading offset not found in database.");

                            AaruConsole.
                            WriteLine($"Combined disc and drive offset are {offsetBytes} bytes ({offsetBytes / 4} samples).");
                        }
                        else
                        {
                            AaruConsole.
                            WriteLine($"Drive reading offset is {driveOffset} bytes ({driveOffset / 4} samples).");

                            AaruConsole.
                            WriteLine($"Combined offset is {offsetBytes} bytes ({offsetBytes / 4} samples)");

                            int?discOffset = offsetBytes - driveOffset;

                            AaruConsole.WriteLine($"Disc offset is {discOffset} bytes ({discOffset / 4} samples)");
                        }
                    }
                }
            }

            dev.Close();
        }
Пример #8
0
 static void DoNvmeMediaInfo(string outputPrefix, Devices.Device dev) =>
 throw new NotImplementedException("NVMe devices not yet supported.");
Пример #9
0
        public static int Invoke(bool debug, bool verbose, string cicmXml, string devicePath, bool resume,
                                 string encoding, bool firstPregap, bool fixOffset, bool force, bool metadata,
                                 bool trim, string outputPath, string options, bool persistent, ushort retryPasses,
                                 uint skip, byte speed, bool stopOnError, string format, string subchannel,
                                 bool @private)
        {
            MainClass.PrintCopyright();

            if (debug)
            {
                AaruConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
            }

            if (verbose)
            {
                AaruConsole.VerboseWriteLineEvent += System.Console.WriteLine;
            }

            Statistics.AddCommand("dump-media");

            AaruConsole.DebugWriteLine("Dump-Media command", "--cicm-xml={0}", cicmXml);
            AaruConsole.DebugWriteLine("Dump-Media command", "--debug={0}", debug);
            AaruConsole.DebugWriteLine("Dump-Media command", "--device={0}", devicePath);
            AaruConsole.DebugWriteLine("Dump-Media command", "--encoding={0}", encoding);
            AaruConsole.DebugWriteLine("Dump-Media command", "--first-pregap={0}", firstPregap);
            AaruConsole.DebugWriteLine("Dump-Media command", "--fix-offset={0}", fixOffset);
            AaruConsole.DebugWriteLine("Dump-Media command", "--force={0}", force);
            AaruConsole.DebugWriteLine("Dump-Media command", "--format={0}", format);
            AaruConsole.DebugWriteLine("Dump-Media command", "--metadata={0}", metadata);
            AaruConsole.DebugWriteLine("Dump-Media command", "--options={0}", options);
            AaruConsole.DebugWriteLine("Dump-Media command", "--output={0}", outputPath);
            AaruConsole.DebugWriteLine("Dump-Media command", "--persistent={0}", persistent);
            AaruConsole.DebugWriteLine("Dump-Media command", "--resume={0}", resume);
            AaruConsole.DebugWriteLine("Dump-Media command", "--retry-passes={0}", retryPasses);
            AaruConsole.DebugWriteLine("Dump-Media command", "--skip={0}", skip);
            AaruConsole.DebugWriteLine("Dump-Media command", "--stop-on-error={0}", stopOnError);
            AaruConsole.DebugWriteLine("Dump-Media command", "--trim={0}", trim);
            AaruConsole.DebugWriteLine("Dump-Media command", "--verbose={0}", verbose);
            AaruConsole.DebugWriteLine("Dump-Media command", "--subchannel={0}", subchannel);
            AaruConsole.DebugWriteLine("Dump-Media command", "--private={0}", @private);

            // TODO: Disabled temporarily
            //AaruConsole.DebugWriteLine("Dump-Media command", "--raw={0}",           raw);

            Dictionary <string, string> parsedOptions = Core.Options.Parse(options);

            AaruConsole.DebugWriteLine("Dump-Media command", "Parsed options:");

            foreach (KeyValuePair <string, string> parsedOption in parsedOptions)
            {
                AaruConsole.DebugWriteLine("Dump-Media command", "{0} = {1}", parsedOption.Key, parsedOption.Value);
            }

            Encoding encodingClass = null;

            if (encoding != null)
            {
                try
                {
                    encodingClass = Claunia.Encoding.Encoding.GetEncoding(encoding);

                    if (verbose)
                    {
                        AaruConsole.VerboseWriteLine("Using encoding for {0}.", encodingClass.EncodingName);
                    }
                }
                catch (ArgumentException)
                {
                    AaruConsole.ErrorWriteLine("Specified encoding is not supported.");

                    return((int)ErrorNumber.EncodingUnknown);
                }
            }

            DumpSubchannel wantedSubchannel = DumpSubchannel.Any;

            switch (subchannel?.ToLowerInvariant())
            {
            case "any":
            case null:
                wantedSubchannel = DumpSubchannel.Any;

                break;

            case "rw":
                wantedSubchannel = DumpSubchannel.Rw;

                break;

            case "rw-or-pq":
                wantedSubchannel = DumpSubchannel.RwOrPq;

                break;

            case "pq":
                wantedSubchannel = DumpSubchannel.Pq;

                break;

            case "none":
                wantedSubchannel = DumpSubchannel.None;

                break;

            default:
                AaruConsole.WriteLine("Incorrect subchannel type \"{0}\" requested.", subchannel);

                break;
            }

            if (devicePath.Length == 2 &&
                devicePath[1] == ':' &&
                devicePath[0] != '/' &&
                char.IsLetter(devicePath[0]))
            {
                devicePath = "\\\\.\\" + char.ToUpper(devicePath[0]) + ':';
            }

            Devices.Device dev;

            try
            {
                dev = new Devices.Device(devicePath);

                if (dev.IsRemote)
                {
                    Statistics.AddRemote(dev.RemoteApplication, dev.RemoteVersion, dev.RemoteOperatingSystem,
                                         dev.RemoteOperatingSystemVersion, dev.RemoteArchitecture);
                }

                if (dev.Error)
                {
                    AaruConsole.ErrorWriteLine(Error.Print(dev.LastError));

                    return((int)ErrorNumber.CannotOpenDevice);
                }
            }
            catch (DeviceException e)
            {
                AaruConsole.ErrorWriteLine(e.Message ?? Error.Print(e.LastError));

                return((int)ErrorNumber.CannotOpenDevice);
            }

            Statistics.AddDevice(dev);

            string outputPrefix = Path.Combine(Path.GetDirectoryName(outputPath),
                                               Path.GetFileNameWithoutExtension(outputPath));

            Resume resumeClass = null;
            var    xs          = new XmlSerializer(typeof(Resume));

            if (File.Exists(outputPrefix + ".resume.xml") && resume)
            {
                try
                {
                    var sr = new StreamReader(outputPrefix + ".resume.xml");
                    resumeClass = (Resume)xs.Deserialize(sr);
                    sr.Close();
                }
                catch
                {
                    AaruConsole.ErrorWriteLine("Incorrect resume file, not continuing...");

                    return((int)ErrorNumber.InvalidResume);
                }
            }

            if (resumeClass != null &&
                resumeClass.NextBlock > resumeClass.LastBlock &&
                resumeClass.BadBlocks.Count == 0 &&
                !resumeClass.Tape)
            {
                AaruConsole.WriteLine("Media already dumped correctly, not continuing...");

                return((int)ErrorNumber.AlreadyDumped);
            }

            CICMMetadataType sidecar = null;
            var sidecarXs            = new XmlSerializer(typeof(CICMMetadataType));

            if (cicmXml != null)
            {
                if (File.Exists(cicmXml))
                {
                    try
                    {
                        var sr = new StreamReader(cicmXml);
                        sidecar = (CICMMetadataType)sidecarXs.Deserialize(sr);
                        sr.Close();
                    }
                    catch
                    {
                        AaruConsole.ErrorWriteLine("Incorrect metadata sidecar file, not continuing...");

                        return((int)ErrorNumber.InvalidSidecar);
                    }
                }
                else
                {
                    AaruConsole.ErrorWriteLine("Could not find metadata sidecar, not continuing...");

                    return((int)ErrorNumber.FileNotFound);
                }
            }

            PluginBase            plugins    = GetPluginBase.Instance;
            List <IWritableImage> candidates = new List <IWritableImage>();

            // Try extension
            if (string.IsNullOrEmpty(format))
            {
                candidates.AddRange(plugins.WritableImages.Values.Where(t =>
                                                                        t.KnownExtensions.
                                                                        Contains(Path.GetExtension(outputPath))));
            }

            // Try Id
            else if (Guid.TryParse(format, out Guid outId))
            {
                candidates.AddRange(plugins.WritableImages.Values.Where(t => t.Id.Equals(outId)));
            }

            // Try name
            else
            {
                candidates.AddRange(plugins.WritableImages.Values.Where(t => string.Equals(t.Name, format,
                                                                                           StringComparison.
                                                                                           InvariantCultureIgnoreCase)));
            }

            if (candidates.Count == 0)
            {
                AaruConsole.WriteLine("No plugin supports requested extension.");

                return((int)ErrorNumber.FormatNotFound);
            }

            if (candidates.Count > 1)
            {
                AaruConsole.WriteLine("More than one plugin supports requested extension.");

                return((int)ErrorNumber.TooManyFormats);
            }

            IWritableImage outputFormat = candidates[0];

            var dumpLog = new DumpLog(outputPrefix + ".log", dev, @private);

            if (verbose)
            {
                dumpLog.WriteLine("Output image format: {0} ({1}).", outputFormat.Name, outputFormat.Id);
                AaruConsole.VerboseWriteLine("Output image format: {0} ({1}).", outputFormat.Name, outputFormat.Id);
            }
            else
            {
                dumpLog.WriteLine("Output image format: {0}.", outputFormat.Name);
                AaruConsole.WriteLine("Output image format: {0}.", outputFormat.Name);
            }

            var dumper = new Dump(resume, dev, devicePath, outputFormat, retryPasses, force, false, persistent,
                                  stopOnError, resumeClass, dumpLog, encodingClass, outputPrefix, outputPath,
                                  parsedOptions, sidecar, skip, metadata, trim, firstPregap, fixOffset, debug,
                                  wantedSubchannel, speed, @private);

            dumper.UpdateStatus         += Progress.UpdateStatus;
            dumper.ErrorMessage         += Progress.ErrorMessage;
            dumper.StoppingErrorMessage += Progress.ErrorMessage;
            dumper.UpdateProgress       += Progress.UpdateProgress;
            dumper.PulseProgress        += Progress.PulseProgress;
            dumper.InitProgress         += Progress.InitProgress;
            dumper.EndProgress          += Progress.EndProgress;
            dumper.InitProgress2        += Progress.InitProgress2;
            dumper.EndProgress2         += Progress.EndProgress2;
            dumper.UpdateProgress2      += Progress.UpdateProgress2;

            System.Console.CancelKeyPress += (sender, e) =>
            {
                e.Cancel = true;
                dumper.Abort();
            };

            dumper.Start();

            dev.Close();

            return((int)ErrorNumber.NoError);
        }
Пример #10
0
        public bool ExecuteTask()
        {
            Tool.Logger.LogDebugInfo("RUN EMULATOR - Initialize", null);
            if (MainClass.Settings.ClearConsoleBeforRuning)
            {
                MainClass.MainWindow.OutputConsole.Clear();
                Tool.Logger.LogDebugInfo("Clear console", null);
            }

            if (MainClass.MainWindow.RunningEmulator)
            {
                output.Add(new TaskMessage(MainClass.Languages.Translate("emulator_is_running"), null, null));
                stateTask = StateEnum.ERROR;
                Tool.Logger.Error(MainClass.Languages.Translate("emulator_is_running"), null);
                return(false);
            }


            if (String.IsNullOrEmpty(MainClass.Workspace.ActualResolution))
            {
                output.Add(new TaskMessage(MainClass.Languages.Translate("pleas_select_resolution"), null, null));
                Tool.Logger.Error(MainClass.Languages.Translate("pleas_select_resolution"), null);
                stateTask = StateEnum.ERROR;
                return(false);
            }

            if (!File.Exists(MainClass.Workspace.ActualResolution))
            {
                output.Add(new TaskMessage(MainClass.Languages.Translate("resolution_file_not_exist", MainClass.Workspace.ActualResolution), null, null));
                Tool.Logger.Error(MainClass.Languages.Translate("resolution_file_not_exist", MainClass.Workspace.ActualResolution), null);
                stateTask = StateEnum.ERROR;
                return(false);
            }

            if (MainClass.Workspace.ActualProject == null)
            {
                output.Add(new TaskMessage(MainClass.Languages.Translate("no_project_selected"), null, null));
                Tool.Logger.Error(MainClass.Languages.Translate("no_project_selected"), null);
                stateTask = StateEnum.ERROR;
                return(false);
            }

            string newPath = System.IO.Path.Combine(MainClass.Settings.EmulatorDirectory, "generic.ini");

            try{
                if (File.Exists(newPath))
                {
                    Tool.Logger.LogDebugInfo(String.Format("Delete File ->{0}", newPath), null);
                    File.Delete(newPath);
                }

                File.Copy(MainClass.Workspace.ActualResolution, newPath);
                Tool.Logger.LogDebugInfo(String.Format("File Copy {0} to {1}", MainClass.Workspace.ActualResolution, newPath), null);

                int selectOs = MainClass.Workspace.ActualDevice;

                Devices.Device d = MainClass.Workspace.ActualProject.DevicesSettings.Find(x => x.TargetPlatformId == selectOs);

                if (d != null)
                {
                    Tool.Logger.LogDebugInfo(String.Format("Device ->{0}", d.Devicetype), null);
                    string font = "";
                    if (d.Includes.Fonts != null && d.Includes.Fonts.Length > 0)
                    {
                        font = string.Join(" ", d.Includes.Fonts);
                        font = font.Replace('/', System.IO.Path.DirectorySeparatorChar);
                        font = font.Replace('\\', System.IO.Path.DirectorySeparatorChar);
                    }
                    using (StreamWriter stream = File.AppendText(newPath)) {
                        stream.WriteLine();
                        string fonts = font;
                        stream.WriteLine("[emulation]");
                        stream.WriteLine("fonts = " + fonts);

                        if (d.Includes.Skin != null)
                        {
                            stream.WriteLine("skin = " + d.Includes.Skin.Name);
                            stream.WriteLine("theme = " + d.Includes.Skin.Theme);
                        }
                        else
                        {
                            stream.WriteLine("skin = ");
                            stream.WriteLine("theme = ");
                        }
                        stream.Flush();
                        stream.Close();
                        stream.Dispose();
                    }
                }
            }catch (Exception ex) {
                //output.Add("Create generic.ini failed!");
                output.Add(new TaskMessage(ex.Message));
                stateTask = StateEnum.ERROR;
                Tool.Logger.Error(ex.Message, null);
                return(false);
            }
            string cmd = "";

            if (MainClass.Settings.EmulatorSettings == null)
            {
                MainClass.Settings.EmulatorSettings           = new Moscrif.IDE.Option.Settings.EmulatorSetting();
                MainClass.Settings.EmulatorSettings.UsDefault = true;
            }

            if (MainClass.Settings.EmulatorSettings.UsDefault)
            {
                if (!GetDefaultCommand(out cmd))
                {
                    return(false);
                }
            }
            else
            {
                cmd = MainClass.Settings.EmulatorSettings.Exec;
            }


            AppFile appFile = MainClass.Workspace.ActualProject.AppFile;
            string  projDir = Path.GetDirectoryName(appFile.ApplicationFile);

            if (!projDir.EndsWith(Path.DirectorySeparatorChar.ToString()))
            {
                projDir += Path.DirectorySeparatorChar;
            }
            string args    = String.Format("/f {0} /d {1} /o console", Path.GetFileName(appFile.ApplicationFile), projDir);
            string wordDir = MainClass.Settings.EmulatorDirectory;

            if (MainClass.Settings.EmulatorSettings.UsDefault)
            {
                wordDir = "";
                if (MainClass.Platform.IsMac)
                {
                    args = String.Format(" -f {0} -d {1} -o console", Path.GetFileName(appFile.ApplicationFile), projDir);

                    Process [] pArry = Process.GetProcesses();
                    foreach (Process p in pArry)
                    {
                        if (p != null)
                        {
                            try {
                                string s = p.ProcessName;
                                s = s.ToLower();

                                if (s.CompareTo("moscrif") == 0)
                                {
                                    Tool.Logger.LogDebugInfo("Kill Emulator Mac", null);
                                    p.Kill();
                                    MainClass.MainWindow.RunningEmulator = false;
                                }
                                //string s = p.ProcessName;
                                //s = s.ToLower();
                                //Console.WriteLine("\t"+s);
                            } catch {                            //(Exception ex){
                                                                 //Console.WriteLine(ex.Message);
                                                                 //Tool.Logger.Error(ex.Message,null);
                            }
                        }
                    }
                }
                else
                {
                    if (MainClass.Platform.IsWindows)
                    {
                        Process [] pArry = Process.GetProcesses();
                        foreach (Process p in pArry)
                        {
                            try{
                                string s = p.ProcessName;
                                s = s.ToLower();

                                if (s.CompareTo("moscrif") == 0)
                                {
                                    Tool.Logger.LogDebugInfo("Kill Emulator win", null);
                                    p.Kill();
                                    MainClass.MainWindow.RunningEmulator = false;
                                }
                            } catch {
                                //Console.WriteLine(ex.Message);
                                //Tool.Logger.Error(ex.Message,null);;
                            }
                        }
                    }
                }
            }
            else
            {
                args = String.Format(MainClass.Settings.EmulatorSettings.Params, Path.GetFileName(appFile.ApplicationFile), projDir);
            }


            try{
                Tool.Logger.LogDebugInfo(String.Format("command ->{0}", cmd), null);
                Tool.Logger.LogDebugInfo(String.Format("arguments ->{0}", args), null);
                Tool.Logger.LogDebugInfo("RUN EMULATOR -Start", null);
                MainClass.MainWindow.RunEmulator(cmd, args, wordDir, ProcessOutputChange);
            }catch (Exception ex) {
                output.Add(new TaskMessage(ex.Message));
                stateTask = StateEnum.ERROR;
                Tool.Logger.Error(ex.Message, null);
                return(false);
            }

            return(true);
        }
Пример #11
0
        static void DoScsiMediaInfo(bool debug, string outputPrefix, Devices.Device dev)
        {
            var scsiInfo = new ScsiInfo(dev);

            if (!scsiInfo.MediaInserted)
            {
                return;
            }

            if (scsiInfo.DeviceInfo.ScsiModeSense6 != null)
            {
                DataFile.WriteTo("Media-Info command", outputPrefix, "_scsi_modesense6.bin", "SCSI MODE SENSE (6)",
                                 scsiInfo.DeviceInfo.ScsiModeSense6);
            }

            if (scsiInfo.DeviceInfo.ScsiModeSense10 != null)
            {
                DataFile.WriteTo("Media-Info command", outputPrefix, "_scsi_modesense10.bin", "SCSI MODE SENSE (10)",
                                 scsiInfo.DeviceInfo.ScsiModeSense10);
            }

            switch (dev.ScsiType)
            {
            case PeripheralDeviceTypes.DirectAccess:
            case PeripheralDeviceTypes.MultiMediaDevice:
            case PeripheralDeviceTypes.OCRWDevice:
            case PeripheralDeviceTypes.OpticalDevice:
            case PeripheralDeviceTypes.SimplifiedDevice:
            case PeripheralDeviceTypes.WriteOnceDevice:
            case PeripheralDeviceTypes.BridgingExpander
                when dev.Model.StartsWith("MDM", StringComparison.Ordinal) ||
                dev.Model.StartsWith("MDH", StringComparison.Ordinal):
                if (scsiInfo.ReadCapacity != null)
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readcapacity.bin", "SCSI READ CAPACITY",
                                     scsiInfo.ReadCapacity);

                if (scsiInfo.ReadCapacity16 != null)
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readcapacity16.bin",
                                     "SCSI READ CAPACITY(16)", scsiInfo.ReadCapacity16);

                if (scsiInfo.Blocks != 0 &&
                    scsiInfo.BlockSize != 0)
                {
                    ulong totalSize = scsiInfo.Blocks * scsiInfo.BlockSize;

                    if (totalSize > 1099511627776)
                    {
                        AaruConsole.WriteLine("Media has {0} blocks of {1} bytes/each. (for a total of {2:F3} TiB)",
                                              scsiInfo.Blocks, scsiInfo.BlockSize, totalSize / 1099511627776d);
                    }
                    else if (totalSize > 1073741824)
                    {
                        AaruConsole.WriteLine("Media has {0} blocks of {1} bytes/each. (for a total of {2:F3} GiB)",
                                              scsiInfo.Blocks, scsiInfo.BlockSize, totalSize / 1073741824d);
                    }
                    else if (totalSize > 1048576)
                    {
                        AaruConsole.WriteLine("Media has {0} blocks of {1} bytes/each. (for a total of {2:F3} MiB)",
                                              scsiInfo.Blocks, scsiInfo.BlockSize, totalSize / 1048576d);
                    }
                    else if (totalSize > 1024)
                    {
                        AaruConsole.WriteLine("Media has {0} blocks of {1} bytes/each. (for a total of {2:F3} KiB)",
                                              scsiInfo.Blocks, scsiInfo.BlockSize, totalSize / 1024d);
                    }
                    else
                    {
                        AaruConsole.WriteLine("Media has {0} blocks of {1} bytes/each. (for a total of {2} bytes)",
                                              scsiInfo.Blocks, scsiInfo.BlockSize, totalSize);
                    }
                }

                break;

            case PeripheralDeviceTypes.SequentialAccess:
                if (scsiInfo.DensitySupport != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_ssc_reportdensitysupport_media.bin",
                                     "SSC REPORT DENSITY SUPPORT (MEDIA)", scsiInfo.DensitySupport);

                    if (scsiInfo.DensitySupportHeader.HasValue)
                    {
                        AaruConsole.WriteLine("Densities supported by currently inserted media:");
                        AaruConsole.WriteLine(DensitySupport.PrettifyDensity(scsiInfo.DensitySupportHeader));
                    }
                }

                if (scsiInfo.MediaTypeSupport != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix,
                                     "_ssc_reportdensitysupport_medium_media.bin",
                                     "SSC REPORT DENSITY SUPPORT (MEDIUM & MEDIA)", scsiInfo.MediaTypeSupport);

                    if (scsiInfo.MediaTypeSupportHeader.HasValue)
                    {
                        AaruConsole.WriteLine("Medium types currently inserted in device:");
                        AaruConsole.WriteLine(DensitySupport.PrettifyMediumType(scsiInfo.MediaTypeSupportHeader));
                    }

                    AaruConsole.WriteLine(DensitySupport.PrettifyMediumType(scsiInfo.MediaTypeSupport));
                }

                break;
            }

            if (dev.ScsiType == PeripheralDeviceTypes.MultiMediaDevice)
            {
                if (scsiInfo.MmcConfiguration != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_getconfiguration_current.bin",
                                     "SCSI GET CONFIGURATION", scsiInfo.MmcConfiguration);
                }

                if (scsiInfo.RecognizedFormatLayers != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_formatlayers.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.RecognizedFormatLayers);
                }

                if (scsiInfo.WriteProtectionStatus != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_writeprotection.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.WriteProtectionStatus);
                }

                if (scsiInfo.DvdPfi != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_pfi.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdPfi);

                    if (scsiInfo.DecodedPfi.HasValue)
                    {
                        AaruConsole.WriteLine("PFI:\n{0}", PFI.Prettify(scsiInfo.DecodedPfi));
                    }
                }

                if (scsiInfo.DvdDmi != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_dmi.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdDmi);

                    if (DMI.IsXbox(scsiInfo.DvdDmi))
                    {
                        AaruConsole.WriteLine("Xbox DMI:\n{0}", DMI.PrettifyXbox(scsiInfo.DvdDmi));
                    }
                    else if (DMI.IsXbox360(scsiInfo.DvdDmi))
                    {
                        AaruConsole.WriteLine("Xbox 360 DMI:\n{0}", DMI.PrettifyXbox360(scsiInfo.DvdDmi));
                    }
                }

                if (scsiInfo.DvdCmi != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_cmi.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdCmi);

                    AaruConsole.WriteLine("Lead-In CMI:\n{0}", CSS_CPRM.PrettifyLeadInCopyright(scsiInfo.DvdCmi));
                }

                if (scsiInfo.DvdDiscKey != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_disckey.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdDiscKey);
                }

                if (scsiInfo.DvdSectorCmi != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_sectorcmi.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdSectorCmi);
                }

                if (scsiInfo.DvdBca != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_bca.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdBca);
                }

                if (scsiInfo.DvdAacs != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_aacs.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdAacs);
                }

                if (scsiInfo.DvdRamDds != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdram_dds.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdRamDds);

                    AaruConsole.WriteLine("Disc Definition Structure:\n{0}", DDS.Prettify(scsiInfo.DvdRamDds));
                }

                if (scsiInfo.DvdRamCartridgeStatus != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdram_status.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdRamCartridgeStatus);

                    AaruConsole.WriteLine("Medium Status:\n{0}", Cartridge.Prettify(scsiInfo.DvdRamCartridgeStatus));
                }

                if (scsiInfo.DvdRamSpareArea != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdram_spare.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdRamSpareArea);

                    AaruConsole.WriteLine("Spare Area Information:\n{0}", Spare.Prettify(scsiInfo.DvdRamSpareArea));
                }

                if (scsiInfo.LastBorderOutRmd != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_lastrmd.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.LastBorderOutRmd);
                }

                if (scsiInfo.DvdPreRecordedInfo != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_pri.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdPreRecordedInfo);

                    if (scsiInfo.DecodedDvdPrePitInformation.HasValue)
                    {
                        AaruConsole.WriteLine("DVD-R(W) Pre-Recorded Information:\n{0}",
                                              PRI.Prettify(scsiInfo.DecodedDvdPrePitInformation));
                    }
                }

                if (scsiInfo.DvdrMediaIdentifier != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdr_mediaid.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdrMediaIdentifier);
                }

                if (scsiInfo.DvdrPhysicalInformation != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdr_pfi.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdrPhysicalInformation);

                    if (scsiInfo.DecodedDvdrPfi.HasValue)
                    {
                        AaruConsole.WriteLine("DVD-R(W) PFI:\n{0}", PFI.Prettify(scsiInfo.DecodedDvdrPfi));
                    }
                }

                if (scsiInfo.DvdPlusAdip != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd+_adip.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdPlusAdip);
                }

                if (scsiInfo.DvdPlusDcb != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd+_dcb.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdPlusDcb);
                }

                if (scsiInfo.HddvdCopyrightInformation != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_hddvd_cmi.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.HddvdCopyrightInformation);
                }

                if (scsiInfo.HddvdrMediumStatus != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_hddvdr_status.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.HddvdrMediumStatus);
                }

                if (scsiInfo.HddvdrLastRmd != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_hddvdr_lastrmd.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.HddvdrLastRmd);
                }

                if (scsiInfo.DvdrLayerCapacity != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvdr_layercap.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdrLayerCapacity);
                }

                if (scsiInfo.DvdrDlMiddleZoneStart != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_mzs.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdrDlMiddleZoneStart);
                }

                if (scsiInfo.DvdrDlJumpIntervalSize != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_jis.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdrDlJumpIntervalSize);
                }

                if (scsiInfo.DvdrDlManualLayerJumpStartLba != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_manuallj.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdrDlManualLayerJumpStartLba);
                }

                if (scsiInfo.DvdrDlRemapAnchorPoint != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_dvd_remapanchor.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.DvdrDlRemapAnchorPoint);
                }

                if (scsiInfo.BlurayDiscInformation != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_di.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.BlurayDiscInformation);

                    AaruConsole.WriteLine("Blu-ray Disc Information:\n{0}",
                                          DI.Prettify(scsiInfo.BlurayDiscInformation));
                }

                if (scsiInfo.BlurayPac != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_pac.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.BlurayPac);
                }

                if (scsiInfo.BlurayBurstCuttingArea != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_bca.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.BlurayBurstCuttingArea);

                    AaruConsole.WriteLine("Blu-ray Burst Cutting Area:\n{0}",
                                          BCA.Prettify(scsiInfo.BlurayBurstCuttingArea));
                }

                if (scsiInfo.BlurayDds != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_dds.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.BlurayDds);

                    AaruConsole.WriteLine("Blu-ray Disc Definition Structure:\n{0}",
                                          Decoders.Bluray.DDS.Prettify(scsiInfo.BlurayDds));
                }

                if (scsiInfo.BlurayCartridgeStatus != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_cartstatus.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.BlurayCartridgeStatus);

                    AaruConsole.WriteLine("Blu-ray Cartridge Status:\n{0}",
                                          Decoders.Bluray.Cartridge.Prettify(scsiInfo.BlurayCartridgeStatus));
                }

                if (scsiInfo.BluraySpareAreaInformation != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_spare.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.BluraySpareAreaInformation);

                    AaruConsole.WriteLine("Blu-ray Spare Area Information:\n{0}",
                                          Decoders.Bluray.Spare.Prettify(scsiInfo.BluraySpareAreaInformation));
                }

                if (scsiInfo.BlurayRawDfl != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscstructure_bd_dfl.bin",
                                     "SCSI READ DISC STRUCTURE", scsiInfo.BlurayRawDfl);
                }

                if (scsiInfo.BlurayTrackResources != null)
                {
                    AaruConsole.WriteLine("Track Resources Information:\n{0}",
                                          DiscInformation.Prettify(scsiInfo.BlurayTrackResources));

                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscinformation_001b.bin",
                                     "SCSI READ DISC INFORMATION", scsiInfo.BlurayTrackResources);
                }

                if (scsiInfo.BlurayPowResources != null)
                {
                    AaruConsole.WriteLine("POW Resources Information:\n{0}",
                                          DiscInformation.Prettify(scsiInfo.BlurayPowResources));

                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscinformation_010b.bin",
                                     "SCSI READ DISC INFORMATION", scsiInfo.BlurayPowResources);
                }

                if (scsiInfo.Toc != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_toc.bin", "SCSI READ TOC/PMA/ATIP",
                                     scsiInfo.Toc);

                    if (scsiInfo.DecodedToc.HasValue)
                    {
                        AaruConsole.WriteLine("TOC:\n{0}", TOC.Prettify(scsiInfo.DecodedToc));
                    }
                }

                if (scsiInfo.Atip != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_atip.bin", "SCSI READ TOC/PMA/ATIP",
                                     scsiInfo.Atip);

                    if (scsiInfo.DecodedAtip != null)
                    {
                        AaruConsole.WriteLine("ATIP:\n{0}", ATIP.Prettify(scsiInfo.DecodedAtip));
                    }
                }

                if (scsiInfo.DiscInformation != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_readdiscinformation_000b.bin",
                                     "SCSI READ DISC INFORMATION", scsiInfo.DiscInformation);

                    if (scsiInfo.DecodedDiscInformation.HasValue)
                    {
                        AaruConsole.WriteLine("Standard Disc Information:\n{0}",
                                              DiscInformation.Prettify000b(scsiInfo.DecodedDiscInformation));
                    }
                }

                if (scsiInfo.Session != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_session.bin", "SCSI READ TOC/PMA/ATIP",
                                     scsiInfo.Session);

                    if (scsiInfo.DecodedSession.HasValue)
                    {
                        AaruConsole.WriteLine("Session information:\n{0}", Session.Prettify(scsiInfo.DecodedSession));
                    }
                }

                if (scsiInfo.RawToc != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_rawtoc.bin", "SCSI READ TOC/PMA/ATIP",
                                     scsiInfo.RawToc);

                    if (scsiInfo.FullToc.HasValue)
                    {
                        AaruConsole.WriteLine("Raw TOC:\n{0}", FullTOC.Prettify(scsiInfo.RawToc));
                    }
                }

                if (scsiInfo.Pma != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_pma.bin", "SCSI READ TOC/PMA/ATIP",
                                     scsiInfo.Pma);

                    AaruConsole.WriteLine("PMA:\n{0}", PMA.Prettify(scsiInfo.Pma));
                }

                if (scsiInfo.CdTextLeadIn != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_cdtext.bin", "SCSI READ TOC/PMA/ATIP",
                                     scsiInfo.CdTextLeadIn);

                    if (scsiInfo.DecodedCdTextLeadIn.HasValue)
                    {
                        AaruConsole.WriteLine("CD-TEXT on Lead-In:\n{0}",
                                              CDTextOnLeadIn.Prettify(scsiInfo.DecodedCdTextLeadIn));
                    }
                }

                if (!string.IsNullOrEmpty(scsiInfo.Mcn))
                {
                    AaruConsole.WriteLine("MCN: {0}", scsiInfo.Mcn);
                }

                if (scsiInfo.Isrcs != null)
                {
                    foreach (KeyValuePair <byte, string> isrc in scsiInfo.Isrcs)
                    {
                        AaruConsole.WriteLine("Track's {0} ISRC: {1}", isrc.Key, isrc.Value);
                    }
                }

                if (scsiInfo.XboxSecuritySector != null)
                {
                    DataFile.WriteTo("Media-Info command", outputPrefix, "_xbox_ss.bin", "KREON EXTRACT SS",
                                     scsiInfo.XboxSecuritySector);
                }

                if (scsiInfo.DecodedXboxSecuritySector.HasValue)
                {
                    AaruConsole.WriteLine("Xbox Security Sector:\n{0}",
                                          SS.Prettify(scsiInfo.DecodedXboxSecuritySector));
                }

                if (scsiInfo.XgdInfo != null)
                {
                    AaruConsole.WriteLine("Video layer 0 size: {0} sectors", scsiInfo.XgdInfo.L0Video);
                    AaruConsole.WriteLine("Video layer 1 size: {0} sectors", scsiInfo.XgdInfo.L1Video);
                    AaruConsole.WriteLine("Middle zone size: {0} sectors", scsiInfo.XgdInfo.MiddleZone);
                    AaruConsole.WriteLine("Game data size: {0} sectors", scsiInfo.XgdInfo.GameSize);
                    AaruConsole.WriteLine("Total size: {0} sectors", scsiInfo.XgdInfo.TotalSize);
                    AaruConsole.WriteLine("Real layer break: {0}", scsiInfo.XgdInfo.LayerBreak);
                    AaruConsole.WriteLine();
                }
            }

            if (scsiInfo.MediaSerialNumber != null)
            {
                DataFile.WriteTo("Media-Info command", outputPrefix, "_mediaserialnumber.bin",
                                 "SCSI READ MEDIA SERIAL NUMBER", scsiInfo.MediaSerialNumber);

                AaruConsole.Write("Media Serial Number: ");

                for (int i = 4; i < scsiInfo.MediaSerialNumber.Length; i++)
                {
                    AaruConsole.Write("{0:X2}", scsiInfo.MediaSerialNumber[i]);
                }

                AaruConsole.WriteLine();
            }

            AaruConsole.WriteLine("Media identified as {0}", scsiInfo.MediaType);
            Statistics.AddMedia(scsiInfo.MediaType, true);

            if (scsiInfo.Toc != null ||
                scsiInfo.RawToc != null)
            {
                Track[] tracks = Dump.GetCdTracks(dev, null, false, out long lastSector, null, null, null, out _, null,
                                                  null);

                if (tracks != null)
                {
                    uint firstLba = (uint)tracks.Min(t => t.TrackStartSector);

                    bool supportsPqSubchannel = Dump.SupportsPqSubchannel(dev, null, null, firstLba);
                    bool supportsRwSubchannel = Dump.SupportsRwSubchannel(dev, null, null, firstLba);

                    // Open main database
                    var ctx = AaruContext.Create(Settings.Settings.MainDbPath);

                    // Search for device in main database
                    Aaru.Database.Models.Device dbDev =
                        ctx.Devices.FirstOrDefault(d => d.Manufacturer == dev.Manufacturer && d.Model == dev.Model &&
                                                   d.Revision == dev.FirmwareRevision);

                    Dump.SolveTrackPregaps(dev, null, null, tracks, supportsPqSubchannel, supportsRwSubchannel, dbDev,
                                           out bool inexactPositioning, false);

                    for (int t = 1; t < tracks.Length; t++)
                    {
                        tracks[t - 1].TrackEndSector = tracks[t].TrackStartSector - 1;
                    }

                    tracks[^ 1].TrackEndSector = (ulong)lastSector;
Пример #12
0
        public static int Invoke(bool debug, bool verbose, string devicePath, string ibgLog, string mhddLog)
        {
            MainClass.PrintCopyright();

            if (debug)
            {
                AaruConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
            }

            if (verbose)
            {
                AaruConsole.VerboseWriteLineEvent += System.Console.WriteLine;
            }

            Statistics.AddCommand("media-scan");

            AaruConsole.DebugWriteLine("Media-Scan command", "--debug={0}", debug);
            AaruConsole.DebugWriteLine("Media-Scan command", "--device={0}", devicePath);
            AaruConsole.DebugWriteLine("Media-Scan command", "--ibg-log={0}", ibgLog);
            AaruConsole.DebugWriteLine("Media-Scan command", "--mhdd-log={0}", mhddLog);
            AaruConsole.DebugWriteLine("Media-Scan command", "--verbose={0}", verbose);

            if (devicePath.Length == 2 &&
                devicePath[1] == ':' &&
                devicePath[0] != '/' &&
                char.IsLetter(devicePath[0]))
            {
                devicePath = "\\\\.\\" + char.ToUpper(devicePath[0]) + ':';
            }

            Devices.Device dev;

            try
            {
                dev = new Devices.Device(devicePath);

                if (dev.IsRemote)
                {
                    Statistics.AddRemote(dev.RemoteApplication, dev.RemoteVersion, dev.RemoteOperatingSystem,
                                         dev.RemoteOperatingSystemVersion, dev.RemoteArchitecture);
                }

                if (dev.Error)
                {
                    AaruConsole.ErrorWriteLine(Error.Print(dev.LastError));

                    return((int)ErrorNumber.CannotOpenDevice);
                }
            }
            catch (DeviceException e)
            {
                AaruConsole.ErrorWriteLine(e.Message);

                return((int)ErrorNumber.CannotOpenDevice);
            }

            Statistics.AddDevice(dev);

            var scanner = new MediaScan(mhddLog, ibgLog, devicePath, dev);

            scanner.UpdateStatus         += Progress.UpdateStatus;
            scanner.StoppingErrorMessage += Progress.ErrorMessage;
            scanner.UpdateProgress       += Progress.UpdateProgress;
            scanner.PulseProgress        += Progress.PulseProgress;
            scanner.InitProgress         += Progress.InitProgress;
            scanner.EndProgress          += Progress.EndProgress;

            System.Console.CancelKeyPress += (sender, e) =>
            {
                e.Cancel = true;
                scanner.Abort();
            };

            ScanResults results = scanner.Scan();

            AaruConsole.WriteLine("Took a total of {0} seconds ({1} processing commands).", results.TotalTime,
                                  results.ProcessingTime);

            AaruConsole.WriteLine("Average speed: {0:F3} MiB/sec.", results.AvgSpeed);
            AaruConsole.WriteLine("Fastest speed burst: {0:F3} MiB/sec.", results.MaxSpeed);
            AaruConsole.WriteLine("Slowest speed burst: {0:F3} MiB/sec.", results.MinSpeed);
            AaruConsole.WriteLine("Summary:");
            AaruConsole.WriteLine("{0} sectors took less than 3 ms.", results.A);
            AaruConsole.WriteLine("{0} sectors took less than 10 ms but more than 3 ms.", results.B);
            AaruConsole.WriteLine("{0} sectors took less than 50 ms but more than 10 ms.", results.C);
            AaruConsole.WriteLine("{0} sectors took less than 150 ms but more than 50 ms.", results.D);
            AaruConsole.WriteLine("{0} sectors took less than 500 ms but more than 150 ms.", results.E);
            AaruConsole.WriteLine("{0} sectors took more than 500 ms.", results.F);
            AaruConsole.WriteLine("{0} sectors could not be read.", results.UnreadableSectors.Count);

            if (results.UnreadableSectors.Count > 0)
            {
                foreach (ulong bad in results.UnreadableSectors)
                {
                    AaruConsole.WriteLine("Sector {0} could not be read", bad);
                }
            }

            AaruConsole.WriteLine();

            if (results.SeekTotal > 0 ||
                results.SeekMin < double.MaxValue ||
                results.SeekMax > double.MinValue)
            {
                AaruConsole.
                WriteLine("Testing {0} seeks, longest seek took {1:F3} ms, fastest one took {2:F3} ms. ({3:F3} ms average)",
                          results.SeekTimes, results.SeekMax, results.SeekMin, results.SeekTotal / 1000);
            }

            dev.Close();

            return((int)ErrorNumber.NoError);
        }