Esempio n. 1
0
        public static void Main(string[] args)
        {
            object[] attributes = typeof(Program).Assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
            AssemblyTitle   = ((AssemblyTitleAttribute)attributes[0]).Title;
            attributes      = typeof(Program).Assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
            AssemblyVersion =
                Attribute.GetCustomAttribute(typeof(Program).Assembly, typeof(AssemblyInformationalVersionAttribute)) as
                AssemblyInformationalVersionAttribute;
            AssemblyCopyright = ((AssemblyCopyrightAttribute)attributes[0]).Copyright;

            Settings.Settings.LoadSettings();

            DicContext ctx = DicContext.Create(Settings.Settings.LocalDbPath);

            ctx.Database.Migrate();
            ctx.SaveChanges();

            // TODO: Update database on GUI

            DicContext mctx = DicContext.Create(Settings.Settings.MasterDbPath);

            mctx.Database.Migrate();
            mctx.SaveChanges();

            Statistics.LoadStats();
            if (Settings.Settings.Current.Stats != null && Settings.Settings.Current.Stats.ShareStats)
            {
                Task.Run(() => { Statistics.SubmitStats(); });
            }

            foreach (string arg in args)
            {
                switch (arg.ToLowerInvariant())
                {
                case "-v":
                case "--verbose":
                    Verbose = true;
                    break;

                case "-d":
                case "--debug":
                    Debug = true;
                    break;
                }
            }

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            new Application(Platforms.Gtk).Run(new frmMain(Debug, Verbose));

            Statistics.SaveStats();
        }
Esempio n. 2
0
        public int Invoke(bool debug, bool verbose, bool clear, bool clearAll)
        {
            if (_masterDbUpdate)
            {
                return((int)ErrorNumber.NoError);
            }

            MainClass.PrintCopyright();

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

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

            DicConsole.DebugWriteLine("Update command", "--debug={0}", debug);
            DicConsole.DebugWriteLine("Update command", "--verbose={0}", verbose);

            if (clearAll)
            {
                try
                {
                    File.Delete(Settings.Settings.LocalDbPath);

                    var ctx = DicContext.Create(Settings.Settings.LocalDbPath);
                    ctx.Database.Migrate();
                    ctx.SaveChanges();
                }
                catch (Exception e)
                {
                    if (Debugger.IsAttached)
                    {
                        throw;
                    }

                    DicConsole.ErrorWriteLine("Could not remove local database.");

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

            if (clear || clearAll)
            {
                try
                {
                    File.Delete(Settings.Settings.MasterDbPath);
                }
                catch (Exception e)
                {
                    if (Debugger.IsAttached)
                    {
                        throw;
                    }

                    DicConsole.ErrorWriteLine("Could not remove master database.");

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

            DoUpdate(clear || clearAll);

            return((int)ErrorNumber.NoError);
        }
Esempio n. 3
0
        public static int Main(string[] args)
        {
            object[] attributes = typeof(MainClass).Assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
            _assemblyTitle = ((AssemblyTitleAttribute)attributes[0]).Title;
            attributes     = typeof(MainClass).Assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);

            _assemblyVersion =
                Attribute.GetCustomAttribute(typeof(MainClass).Assembly, typeof(AssemblyInformationalVersionAttribute))
                as AssemblyInformationalVersionAttribute;

            _assemblyCopyright = ((AssemblyCopyrightAttribute)attributes[0]).Copyright;

            DicConsole.WriteLineEvent      += System.Console.WriteLine;
            DicConsole.WriteEvent          += System.Console.Write;
            DicConsole.ErrorWriteLineEvent += System.Console.Error.WriteLine;

            Settings.Settings.LoadSettings();

            var ctx = DicContext.Create(Settings.Settings.LocalDbPath);

            ctx.Database.Migrate();
            ctx.SaveChanges();

            bool masterDbUpdate = false;

            if (!File.Exists(Settings.Settings.MasterDbPath))
            {
                masterDbUpdate = true;
                UpdateCommand.DoUpdate(true);
            }

            var masterContext = DicContext.Create(Settings.Settings.MasterDbPath);

            if (masterContext.Database.GetPendingMigrations().Any())
            {
                DicConsole.WriteLine("New database version, updating...");

                try
                {
                    File.Delete(Settings.Settings.MasterDbPath);
                }
                catch (Exception)
                {
                    DicConsole.ErrorWriteLine("Exception trying to remove old database version, cannot continue...");
                    DicConsole.ErrorWriteLine("Please manually remove file at {0}", Settings.Settings.MasterDbPath);
                }

                UpdateCommand.DoUpdate(true);
            }

            if ((args.Length < 1 || args[0].ToLowerInvariant() != "gui") &&
                Settings.Settings.Current.GdprCompliance < DicSettings.GdprLevel)
            {
                new ConfigureCommand(true, true).Invoke(args);
            }

            Statistics.LoadStats();

            if (Settings.Settings.Current.Stats != null &&
                Settings.Settings.Current.Stats.ShareStats)
            {
                Task.Run(Statistics.SubmitStats);
            }

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            Statistics.SaveStats();

            var rootCommand = new RootCommand
            {
                new Option(new[]
                {
                    "--verbose", "-v"
                }, "Shows verbose output.")
                {
                    Argument = new Argument <bool>(() => false)
                },
                new Option(new[]
                {
                    "--debug", "-d"
                }, "Shows debug output from plugins.")
                {
                    Argument = new Argument <bool>(() => false)
                }
            };

            rootCommand.Description =
                $"{_assemblyTitle} {_assemblyVersion?.InformationalVersion}\n{_assemblyCopyright}";

            rootCommand.AddCommand(new DatabaseFamily(masterDbUpdate));
            rootCommand.AddCommand(new DeviceFamily());
            rootCommand.AddCommand(new FilesystemFamily());
            rootCommand.AddCommand(new ImageFamily());
            rootCommand.AddCommand(new MediaFamily());

            rootCommand.AddCommand(new ConfigureCommand(false, false));
            rootCommand.AddCommand(new FormatsCommand());
            rootCommand.AddCommand(new ListEncodingsCommand());
            rootCommand.AddCommand(new ListNamespacesCommand());
            rootCommand.AddCommand(new RemoteCommand());

            return(rootCommand.Invoke(args));
        }
        public dlgStatistics()
        {
            XamlReader.Load(this);

            DicContext ctx = DicContext.Create(Settings.Settings.LocalDbPath);

            if (ctx.Commands.Any())
            {
                if (ctx.Commands.Any(c => c.Name == "analyze"))
                {
                    ulong count = ctx.Commands.Where(c => c.Name == "analyze" && c.Synchronized).Select(c => c.Count)
                                  .FirstOrDefault();
                    count += (ulong)ctx.Commands.LongCount(c => c.Name == "analyze" && !c.Synchronized);

                    lblAnalyze.Visible = true;
                    lblAnalyze.Text    = $"You have called the Analyze command {count} times";
                }

                if (ctx.Commands.Any(c => c.Name == "benchmark"))
                {
                    ulong count = ctx.Commands.Where(c => c.Name == "benchmark" && c.Synchronized).Select(c => c.Count)
                                  .FirstOrDefault();
                    count += (ulong)ctx.Commands.LongCount(c => c.Name == "benchmark" && !c.Synchronized);

                    lblBenchmark.Visible = true;
                    lblBenchmark.Text    = $"You have called the Benchmark command {count} times";
                }

                if (ctx.Commands.Any(c => c.Name == "checksum"))
                {
                    ulong count = ctx.Commands.Where(c => c.Name == "checksum" && c.Synchronized).Select(c => c.Count)
                                  .FirstOrDefault();
                    count += (ulong)ctx.Commands.LongCount(c => c.Name == "checksum" && !c.Synchronized);

                    lblChecksum.Visible = true;
                    lblChecksum.Text    = $"You have called the Checksum command {count} times";
                }

                if (ctx.Commands.Any(c => c.Name == "compare"))
                {
                    ulong count = ctx.Commands.Where(c => c.Name == "compare" && c.Synchronized).Select(c => c.Count)
                                  .FirstOrDefault();
                    count += (ulong)ctx.Commands.LongCount(c => c.Name == "compare" && !c.Synchronized);

                    lblCompare.Visible = true;
                    lblCompare.Text    = $"You have called the Compare command {count} times";
                }

                if (ctx.Commands.Any(c => c.Name == "convert-image"))
                {
                    ulong count = ctx.Commands.Where(c => c.Name == "convert-image" && c.Synchronized)
                                  .Select(c => c.Count).FirstOrDefault();
                    count += (ulong)ctx.Commands.LongCount(c => c.Name == "convert-image" && !c.Synchronized);

                    lblConvertImage.Visible = true;
                    lblConvertImage.Text    = $"You have called the Convert-Image command {count} times";
                }

                if (ctx.Commands.Any(c => c.Name == "create-sidecar"))
                {
                    ulong count = ctx.Commands.Where(c => c.Name == "create-sidecar" && c.Synchronized)
                                  .Select(c => c.Count).FirstOrDefault();
                    count += (ulong)ctx.Commands.LongCount(c => c.Name == "create-sidecar" && !c.Synchronized);

                    lblCreateSidecar.Visible = true;
                    lblCreateSidecar.Text    = $"You have called the Create-Sidecar command {count} times";
                }

                if (ctx.Commands.Any(c => c.Name == "decode"))
                {
                    ulong count = ctx.Commands.Where(c => c.Name == "decode" && c.Synchronized).Select(c => c.Count)
                                  .FirstOrDefault();
                    count += (ulong)ctx.Commands.LongCount(c => c.Name == "decode" && !c.Synchronized);

                    lblDecode.Visible = true;
                    lblDecode.Text    = $"You have called the Decode command {count} times";
                }

                if (ctx.Commands.Any(c => c.Name == "device-info"))
                {
                    ulong count = ctx.Commands.Where(c => c.Name == "device-info" && c.Synchronized)
                                  .Select(c => c.Count).FirstOrDefault();
                    count += (ulong)ctx.Commands.LongCount(c => c.Name == "device-info" && !c.Synchronized);

                    lblDeviceInfo.Visible = true;
                    lblDeviceInfo.Text    = $"You have called the Device-Info command {count} times";
                }

                if (ctx.Commands.Any(c => c.Name == "device-report"))
                {
                    ulong count = ctx.Commands.Where(c => c.Name == "device-report" && c.Synchronized)
                                  .Select(c => c.Count).FirstOrDefault();
                    count += (ulong)ctx.Commands.LongCount(c => c.Name == "device-report" && !c.Synchronized);

                    lblDeviceReport.Visible = true;
                    lblDeviceReport.Text    = $"You have called the Device-Report command {count} times";
                }

                if (ctx.Commands.Any(c => c.Name == "dump-media"))
                {
                    ulong count = ctx.Commands.Where(c => c.Name == "dump-media" && c.Synchronized).Select(c => c.Count)
                                  .FirstOrDefault();
                    count += (ulong)ctx.Commands.LongCount(c => c.Name == "dump-media" && !c.Synchronized);

                    lblDumpMedia.Visible = true;
                    lblDumpMedia.Text    = $"You have called the Dump-Media command {count} times";
                }

                if (ctx.Commands.Any(c => c.Name == "entropy"))
                {
                    ulong count = ctx.Commands.Where(c => c.Name == "entropy" && c.Synchronized).Select(c => c.Count)
                                  .FirstOrDefault();
                    count += (ulong)ctx.Commands.LongCount(c => c.Name == "entropy" && !c.Synchronized);

                    lblEntropy.Visible = true;
                    lblEntropy.Text    = $"You have called the Entropy command {count} times";
                }

                if (ctx.Commands.Any(c => c.Name == "formats"))
                {
                    ulong count = ctx.Commands.Where(c => c.Name == "formats" && c.Synchronized).Select(c => c.Count)
                                  .FirstOrDefault();
                    count += (ulong)ctx.Commands.LongCount(c => c.Name == "formats" && !c.Synchronized);

                    lblFormats.Visible = true;
                    lblFormats.Text    = $"You have called the Formats command {count} times";
                }

                if (ctx.Commands.Any(c => c.Name == "image-info"))
                {
                    ulong count = ctx.Commands.Where(c => c.Name == "image-info" && c.Synchronized).Select(c => c.Count)
                                  .FirstOrDefault();
                    count += (ulong)ctx.Commands.LongCount(c => c.Name == "image-info" && !c.Synchronized);

                    lblImageInfo.Visible = true;
                    lblImageInfo.Text    = $"You have called the Image-Info command {count} times";
                }

                if (ctx.Commands.Any(c => c.Name == "media-info"))
                {
                    ulong count = ctx.Commands.Where(c => c.Name == "media-info" && c.Synchronized).Select(c => c.Count)
                                  .FirstOrDefault();
                    count += (ulong)ctx.Commands.LongCount(c => c.Name == "media-info" && !c.Synchronized);

                    lblMediaInfo.Visible = true;
                    lblMediaInfo.Text    = $"You have called the Media-Info command {count} times";
                }

                if (ctx.Commands.Any(c => c.Name == "media-scan"))
                {
                    ulong count = ctx.Commands.Where(c => c.Name == "media-scan" && c.Synchronized).Select(c => c.Count)
                                  .FirstOrDefault();
                    count += (ulong)ctx.Commands.LongCount(c => c.Name == "media-scan" && !c.Synchronized);

                    lblMediaScan.Visible = true;
                    lblMediaScan.Text    = $"You have called the Media-Scan command {count} times";
                }

                if (ctx.Commands.Any(c => c.Name == "printhex"))
                {
                    ulong count = ctx.Commands.Where(c => c.Name == "printhex" && c.Synchronized).Select(c => c.Count)
                                  .FirstOrDefault();
                    count += (ulong)ctx.Commands.LongCount(c => c.Name == "printhex" && !c.Synchronized);

                    lblPrintHex.Visible = true;
                    lblPrintHex.Text    = $"You have called the Print-Hex command {count} times";
                }

                if (ctx.Commands.Any(c => c.Name == "verify"))
                {
                    ulong count = ctx.Commands.Where(c => c.Name == "verify" && c.Synchronized).Select(c => c.Count)
                                  .FirstOrDefault();
                    count += (ulong)ctx.Commands.LongCount(c => c.Name == "verify" && !c.Synchronized);

                    lblVerify.Visible = true;
                    lblVerify.Text    = $"You have called the Verify command {count} times";
                }

                tabCommands.Visible = lblAnalyze.Visible || lblBenchmark.Visible || lblChecksum.Visible ||
                                      lblCompare.Visible || lblConvertImage.Visible || lblCreateSidecar.Visible ||
                                      lblDecode.Visible || lblDeviceInfo.Visible || lblDeviceReport.Visible ||
                                      lblDumpMedia.Visible || lblEntropy.Visible || lblFormats.Visible ||
                                      lblImageInfo.Visible || lblMediaInfo.Visible || lblMediaScan.Visible ||
                                      lblPrintHex.Visible || lblVerify.Visible;
            }

            if (ctx.Filters.Any())
            {
                tabFilters.Visible = true;

                TreeGridItemCollection filterList = new TreeGridItemCollection();

                treeFilters.Columns.Add(new GridColumn {
                    HeaderText = "Filter", DataCell = new TextBoxCell(0)
                });
                treeFilters.Columns.Add(new GridColumn {
                    HeaderText = "Times found", DataCell = new TextBoxCell(1)
                });

                treeFilters.AllowMultipleSelection = false;
                treeFilters.ShowHeader             = true;
                treeFilters.DataStore = filterList;

                foreach (string nvs in ctx.Filters.Select(n => n.Name).Distinct())
                {
                    ulong count = ctx.Filters.Where(c => c.Name == nvs && c.Synchronized).Select(c => c.Count)
                                  .FirstOrDefault();
                    count += (ulong)ctx.Filters.LongCount(c => c.Name == nvs && !c.Synchronized);

                    filterList.Add(new TreeGridItem {
                        Values = new object[] { nvs, count }
                    });
                }
            }

            if (ctx.MediaFormats.Any())
            {
                tabFormats.Visible = true;

                TreeGridItemCollection formatList = new TreeGridItemCollection();

                treeFormats.Columns.Add(new GridColumn {
                    HeaderText = "Format", DataCell = new TextBoxCell(0)
                });
                treeFormats.Columns.Add(new GridColumn {
                    HeaderText = "Times found", DataCell = new TextBoxCell(1)
                });

                treeFormats.AllowMultipleSelection = false;
                treeFormats.ShowHeader             = true;
                treeFormats.DataStore = formatList;

                foreach (string nvs in ctx.MediaFormats.Select(n => n.Name).Distinct())
                {
                    ulong count = ctx.MediaFormats.Where(c => c.Name == nvs && c.Synchronized).Select(c => c.Count)
                                  .FirstOrDefault();
                    count += (ulong)ctx.MediaFormats.LongCount(c => c.Name == nvs && !c.Synchronized);

                    formatList.Add(new TreeGridItem {
                        Values = new object[] { nvs, count }
                    });
                }
            }

            if (ctx.Partitions.Any())
            {
                tabPartitions.Visible = true;

                TreeGridItemCollection partitionList = new TreeGridItemCollection();

                treePartitions.Columns.Add(new GridColumn {
                    HeaderText = "Filter", DataCell = new TextBoxCell(0)
                });
                treePartitions.Columns.Add(new GridColumn {
                    HeaderText = "Times found", DataCell = new TextBoxCell(1)
                });

                treePartitions.AllowMultipleSelection = false;
                treePartitions.ShowHeader             = true;
                treePartitions.DataStore = partitionList;

                foreach (string nvs in ctx.Partitions.Select(n => n.Name).Distinct())
                {
                    ulong count = ctx.Partitions.Where(c => c.Name == nvs && c.Synchronized).Select(c => c.Count)
                                  .FirstOrDefault();
                    count += (ulong)ctx.Partitions.LongCount(c => c.Name == nvs && !c.Synchronized);

                    partitionList.Add(new TreeGridItem {
                        Values = new object[] { nvs, count }
                    });
                }
            }

            if (ctx.Filesystems.Any())
            {
                tabFilesystems.Visible = true;

                TreeGridItemCollection filesystemList = new TreeGridItemCollection();

                treeFilesystems.Columns.Add(new GridColumn {
                    HeaderText = "Filesystem", DataCell = new TextBoxCell(0)
                });
                treeFilesystems.Columns.Add(new GridColumn {
                    HeaderText = "Times found", DataCell = new TextBoxCell(1)
                });

                treeFilesystems.AllowMultipleSelection = false;
                treeFilesystems.ShowHeader             = true;
                treeFilesystems.DataStore = filesystemList;

                foreach (string nvs in ctx.Filesystems.Select(n => n.Name).Distinct())
                {
                    ulong count = ctx.Filesystems.Where(c => c.Name == nvs && c.Synchronized).Select(c => c.Count)
                                  .FirstOrDefault();
                    count += (ulong)ctx.Filesystems.LongCount(c => c.Name == nvs && !c.Synchronized);

                    filesystemList.Add(new TreeGridItem {
                        Values = new object[] { nvs, count }
                    });
                }
            }

            if (ctx.SeenDevices.Any())
            {
                tabDevices.Visible = true;

                TreeGridItemCollection deviceList = new TreeGridItemCollection();

                treeDevices.Columns.Add(new GridColumn {
                    HeaderText = "Device", DataCell = new TextBoxCell(0)
                });
                treeDevices.Columns.Add(new GridColumn {
                    HeaderText = "Manufacturer", DataCell = new TextBoxCell(1)
                });
                treeDevices.Columns.Add(new GridColumn {
                    HeaderText = "Revision", DataCell = new TextBoxCell(2)
                });
                treeDevices.Columns.Add(new GridColumn {
                    HeaderText = "Bus", DataCell = new TextBoxCell(3)
                });

                treeDevices.AllowMultipleSelection = false;
                treeDevices.ShowHeader             = true;
                treeDevices.DataStore = deviceList;

                foreach (DeviceStat ds in ctx.SeenDevices.OrderBy(n => n.Manufacturer).ThenBy(n => n.Manufacturer)
                         .ThenBy(n => n.Revision)
                         .ThenBy(n => n.Bus))
                {
                    deviceList.Add(new TreeGridItem
                    {
                        Values = new object[] { ds.Model, ds.Manufacturer, ds.Revision, ds.Bus }
                    });
                }
            }

            if (!ctx.Medias.Any())
            {
                return;
            }

            tabMedias.Visible = true;

            TreeGridItemCollection mediaList = new TreeGridItemCollection();

            treeMedias.Columns.Add(new GridColumn {
                HeaderText = "Media", DataCell = new TextBoxCell(0)
            });
            treeMedias.Columns.Add(new GridColumn {
                HeaderText = "Times found", DataCell = new TextBoxCell(1)
            });
            treeMedias.Columns.Add(new GridColumn {
                HeaderText = "Type", DataCell = new TextBoxCell(2)
            });

            treeMedias.AllowMultipleSelection = false;
            treeMedias.ShowHeader             = true;
            treeMedias.DataStore = mediaList;

            foreach (string media in ctx.Medias.OrderBy(ms => ms.Type).Select(ms => ms.Type).Distinct())
            {
                ulong count = ctx.Medias.Where(c => c.Type == media && c.Synchronized && c.Real).Select(c => c.Count)
                              .FirstOrDefault();
                count += (ulong)ctx.Medias.LongCount(c => c.Type == media && !c.Synchronized && c.Real);

                if (count > 0)
                {
                    mediaList.Add(new TreeGridItem {
                        Values = new object[] { media, count, "real" }
                    });
                }

                count = ctx.Medias.Where(c => c.Type == media && c.Synchronized && !c.Real).Select(c => c.Count)
                        .FirstOrDefault();
                count += (ulong)ctx.Medias.LongCount(c => c.Type == media && !c.Synchronized && !c.Real);

                if (count == 0)
                {
                    continue;
                }

                mediaList.Add(new TreeGridItem {
                    Values = new object[] { media, count, "image" }
                });
            }
        }
Esempio n. 5
0
        public static void UpdateMasterDatabase(bool create)
        {
            DicContext mctx = DicContext.Create(Settings.Settings.MasterDbPath);

            mctx.Database.Migrate();
            mctx.SaveChanges();

            try
            {
                long     lastUpdate = 0;
                DateTime latest     = DateTime.MinValue;

                if (!create)
                {
                    List <DateTime> latestAll = new List <DateTime>();
                    if (mctx.UsbVendors.Any())
                    {
                        latestAll.Add(mctx.UsbVendors.Max(v => v.ModifiedWhen));
                    }
                    if (mctx.UsbProducts.Any())
                    {
                        latestAll.Add(mctx.UsbProducts.Max(p => p.ModifiedWhen));
                    }
                    if (mctx.CdOffsets.Any())
                    {
                        latestAll.Add(mctx.CdOffsets.Max(o => o.ModifiedWhen));
                    }
                    if (mctx.Devices.Any())
                    {
                        latestAll.Add(mctx.Devices.Max(d => d.LastSynchronized));
                    }

                    if (latestAll.Any())
                    {
                        latest     = latestAll.Max(t => t);
                        lastUpdate = (latest.ToFileTimeUtc() - new DateTime(1970, 1, 1).ToFileTimeUtc()) / 10000000;
                    }
                }

                if (lastUpdate == 0)
                {
                    create = true;
                    DicConsole.WriteLine("Creating master database");
                }
                else
                {
                    DicConsole.WriteLine("Updating master database");
                    DicConsole.WriteLine("Last update: {0}", latest);
                }

                DateTime updateStart = DateTime.UtcNow;

                WebRequest request =
                    WebRequest.Create($"https://www.discimagechef.app/api/update?timestamp={lastUpdate}");
                ((HttpWebRequest)request).UserAgent = $"DiscImageChef {typeof(Version).Assembly.GetName().Version}";
                request.Method      = "GET";
                request.ContentType = "application/json";
                WebResponse response = request.GetResponse();

                if (((HttpWebResponse)response).StatusCode != HttpStatusCode.OK)
                {
                    DicConsole.ErrorWriteLine("Error {0} when trying to get updated entities.",
                                              ((HttpWebResponse)response).StatusCode);
                    return;
                }

                Stream       data   = response.GetResponseStream();
                StreamReader reader = new StreamReader(data ?? throw new InvalidOperationException());
                SyncDto      sync   = JsonConvert.DeserializeObject <SyncDto>(reader.ReadToEnd());

                if (create)
                {
                    DicConsole.WriteLine("Adding USB vendors");
                    foreach (UsbVendorDto vendor in sync.UsbVendors)
                    {
                        mctx.UsbVendors.Add(new UsbVendor(vendor.VendorId, vendor.Vendor));
                    }

                    DicConsole.WriteLine("Added {0} usb vendors", sync.UsbVendors.Count);

                    DicConsole.WriteLine("Adding USB products");
                    foreach (UsbProductDto product in sync.UsbProducts)
                    {
                        mctx.UsbProducts.Add(new UsbProduct(product.VendorId, product.ProductId, product.Product));
                    }

                    DicConsole.WriteLine("Added {0} usb products", sync.UsbProducts.Count);

                    DicConsole.WriteLine("Adding CompactDisc read offsets");
                    foreach (CdOffsetDto offset in sync.Offsets)
                    {
                        mctx.CdOffsets.Add(new CdOffset(offset)
                        {
                            Id = offset.Id
                        });
                    }

                    DicConsole.WriteLine("Added {0} CompactDisc read offsets", sync.Offsets.Count);

                    DicConsole.WriteLine("Adding known devices");
                    foreach (DeviceDto device in sync.Devices)
                    {
                        mctx.Devices.Add(new Device(device)
                        {
                            Id = device.Id
                        });
                    }

                    DicConsole.WriteLine("Added {0} known devices", sync.Devices.Count);
                }
                else
                {
                    long addedVendors     = 0;
                    long addedProducts    = 0;
                    long addedOffsets     = 0;
                    long addedDevices     = 0;
                    long modifiedVendors  = 0;
                    long modifiedProducts = 0;
                    long modifiedOffsets  = 0;
                    long modifiedDevices  = 0;

                    DicConsole.WriteLine("Updating USB vendors");
                    foreach (UsbVendorDto vendor in sync.UsbVendors)
                    {
                        UsbVendor existing = mctx.UsbVendors.FirstOrDefault(v => v.Id == vendor.VendorId);

                        if (existing != null)
                        {
                            modifiedVendors++;
                            existing.Vendor       = vendor.Vendor;
                            existing.ModifiedWhen = updateStart;
                            mctx.UsbVendors.Update(existing);
                        }
                        else
                        {
                            addedVendors++;
                            mctx.UsbVendors.Add(new UsbVendor(vendor.VendorId, vendor.Vendor));
                        }
                    }

                    DicConsole.WriteLine("Added {0} USB vendors", addedVendors);
                    DicConsole.WriteLine("Modified {0} USB vendors", modifiedVendors);

                    DicConsole.WriteLine("Updating USB products");
                    foreach (UsbProductDto product in sync.UsbProducts)
                    {
                        UsbProduct existing =
                            mctx.UsbProducts.FirstOrDefault(p => p.VendorId == product.VendorId &&
                                                            p.ProductId == product.ProductId);

                        if (existing != null)
                        {
                            modifiedProducts++;
                            existing.Product      = product.Product;
                            existing.ModifiedWhen = updateStart;
                            mctx.UsbProducts.Update(existing);
                        }
                        else
                        {
                            addedProducts++;
                            mctx.UsbProducts.Add(new UsbProduct(product.VendorId, product.ProductId, product.Product));
                        }
                    }

                    DicConsole.WriteLine("Added {0} USB products", addedProducts);
                    DicConsole.WriteLine("Modified {0} USB products", modifiedProducts);

                    DicConsole.WriteLine("Updating CompactDisc read offsets");
                    foreach (CdOffsetDto offset in sync.Offsets)
                    {
                        CdOffset existing = mctx.CdOffsets.FirstOrDefault(o => o.Id == offset.Id);

                        if (existing != null)
                        {
                            modifiedOffsets++;
                            existing.Agreement    = offset.Agreement;
                            existing.Manufacturer = offset.Manufacturer;
                            existing.Model        = offset.Model;
                            existing.Submissions  = offset.Submissions;
                            existing.Offset       = offset.Offset;
                            existing.ModifiedWhen = updateStart;
                            mctx.CdOffsets.Update(existing);
                        }
                        else
                        {
                            addedOffsets++;
                            mctx.CdOffsets.Add(new CdOffset(offset)
                            {
                                Id = offset.Id
                            });
                        }
                    }

                    DicConsole.WriteLine("Added {0} CompactDisc read offsets", addedOffsets);
                    DicConsole.WriteLine("Modified {0} CompactDisc read offsets", modifiedOffsets);

                    DicConsole.WriteLine("Updating known devices");
                    foreach (DeviceDto device in sync.Devices)
                    {
                        Device existing = mctx.Devices.FirstOrDefault(d => d.Id == device.Id);

                        if (existing != null)
                        {
                            modifiedDevices++;

                            mctx.Remove(existing);

                            existing = new Device(device)
                            {
                                Id = device.Id, OptimalMultipleSectorsRead = device.OptimalMultipleSectorsRead
                            };

                            mctx.Devices.Add(existing);
                        }
                        else
                        {
                            addedDevices++;
                            mctx.Devices.Add(new Device(device)
                            {
                                Id = device.Id,
                                OptimalMultipleSectorsRead = device.OptimalMultipleSectorsRead
                            });
                        }
                    }

                    DicConsole.WriteLine("Added {0} known devices", addedDevices);
                    DicConsole.WriteLine("Modified {0} known devices", modifiedDevices);
                }
            }
            catch (Exception ex) { DicConsole.ErrorWriteLine("Exception {0} when updating database.", ex); }
            finally
            {
                DicConsole.WriteLine("Saving changes...");
                mctx.SaveChanges();
            }
        }
Esempio n. 6
0
        public static int Main(string[] args)
        {
            var attributes = typeof(MainClass).Assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false);

            AssemblyTitle   = ((AssemblyTitleAttribute)attributes[0]).Title;
            attributes      = typeof(MainClass).Assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
            AssemblyVersion =
                Attribute.GetCustomAttribute(typeof(MainClass).Assembly, typeof(AssemblyInformationalVersionAttribute))
                as AssemblyInformationalVersionAttribute;
            AssemblyCopyright = ((AssemblyCopyrightAttribute)attributes[0]).Copyright;

            DicConsole.WriteLineEvent      += System.Console.WriteLine;
            DicConsole.WriteEvent          += System.Console.Write;
            DicConsole.ErrorWriteLineEvent += System.Console.Error.WriteLine;

            Settings.Settings.LoadSettings();

            var ctx = DicContext.Create(Settings.Settings.LocalDbPath);

            ctx.Database.Migrate();
            ctx.SaveChanges();

            var masterDbUpdate = false;

            if (!File.Exists(Settings.Settings.MasterDbPath))
            {
                masterDbUpdate = true;
                UpdateCommand.DoUpdate(true);
            }

            var mctx = DicContext.Create(Settings.Settings.MasterDbPath);

            mctx.Database.Migrate();
            mctx.SaveChanges();

            if ((args.Length < 1 || args[0].ToLowerInvariant() != "gui") &&
                Settings.Settings.Current.GdprCompliance < DicSettings.GdprLevel)
            {
                new ConfigureCommand(true, true).Invoke(args);
            }
            Statistics.LoadStats();
            if (Settings.Settings.Current.Stats != null && Settings.Settings.Current.Stats.ShareStats)
            {
                Task.Run(() => { Statistics.SubmitStats(); });
            }

            var currentPlatform = DetectOS.GetRealPlatformID();

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            var commands = new CommandSet("DiscImageChef")
            {
                $"{AssemblyTitle} {AssemblyVersion?.InformationalVersion}",
                $"{AssemblyCopyright}",
                "",
                "usage: DiscImageChef COMMAND [OPTIONS]",
                "",
                "Global options:",
                { "verbose|v", "Shows verbose output.", b => Verbose = b != null },
                { "debug|d", "Shows debug output from plugins.", b => Debug = b != null },
                "",
                "Available commands:",
                new AnalyzeCommand(),
                new BenchmarkCommand(),
                new ChecksumCommand(),
                new CompareCommand(),
                new ConfigureCommand(false, false),
                new ConvertImageCommand(),
                new CreateSidecarCommand(),
                new DecodeCommand()
            };

            if (currentPlatform == PlatformID.FreeBSD || currentPlatform == PlatformID.Linux ||
                currentPlatform == PlatformID.Win32NT)
            {
                commands.Add(new DeviceInfoCommand());
                commands.Add(new DeviceReportCommand());
                commands.Add(new DumpMediaCommand());
            }

            commands.Add(new EntropyCommand());
            commands.Add(new ExtractFilesCommand());
            commands.Add(new FormatsCommand());
            commands.Add(new ImageInfoCommand());

            if (currentPlatform == PlatformID.FreeBSD || currentPlatform == PlatformID.Linux ||
                currentPlatform == PlatformID.Win32NT)
            {
                commands.Add(new ListDevicesCommand());
            }

            commands.Add(new ListEncodingsCommand());
            commands.Add(new ListNamespacesCommand());
            commands.Add(new ListOptionsCommand());
            commands.Add(new LsCommand());

            if (currentPlatform == PlatformID.FreeBSD || currentPlatform == PlatformID.Linux ||
                currentPlatform == PlatformID.Win32NT)
            {
                commands.Add(new MediaInfoCommand());
                commands.Add(new MediaScanCommand());
            }

            commands.Add(new PrintHexCommand());
            commands.Add(new StatisticsCommand());
            commands.Add(new UpdateCommand(masterDbUpdate));
            commands.Add(new VerifyCommand());
            commands.Add(new RemoteCommand());

            var ret = commands.Run(args);

            Statistics.SaveStats();

            return(ret);
        }
Esempio n. 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)
                {
                    DicConsole.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)
                    {
                        DicConsole.WriteLine("Densities supported by currently inserted media:");
                        DicConsole.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)
                    {
                        DicConsole.WriteLine("Medium types currently inserted in device:");
                        DicConsole.WriteLine(DensitySupport.PrettifyMediumType(scsiInfo.MediaTypeSupportHeader));
                    }

                    DicConsole.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)
                    {
                        DicConsole.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))
                    {
                        DicConsole.WriteLine("Xbox DMI:\n{0}", DMI.PrettifyXbox(scsiInfo.DvdDmi));
                    }
                    else if (DMI.IsXbox360(scsiInfo.DvdDmi))
                    {
                        DicConsole.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);

                    DicConsole.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);

                    DicConsole.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);

                    DicConsole.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);

                    DicConsole.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);

                    DicConsole.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);

                    DicConsole.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);

                    DicConsole.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);

                    DicConsole.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);

                    DicConsole.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)
                {
                    DicConsole.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)
                {
                    DicConsole.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)
                    {
                        DicConsole.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)
                    {
                        DicConsole.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)
                    {
                        DicConsole.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)
                    {
                        DicConsole.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)
                    {
                        DicConsole.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);

                    DicConsole.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)
                    {
                        DicConsole.WriteLine("CD-TEXT on Lead-In:\n{0}",
                                             CDTextOnLeadIn.Prettify(scsiInfo.DecodedCdTextLeadIn));
                    }
                }

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

                if (scsiInfo.Isrcs != null)
                {
                    foreach (KeyValuePair <byte, string> isrc in scsiInfo.Isrcs)
                    {
                        DicConsole.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)
                {
                    DicConsole.WriteLine("Xbox Security Sector:\n{0}", SS.Prettify(scsiInfo.DecodedXboxSecuritySector));
                }

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

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

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

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

                DicConsole.WriteLine();
            }

            DicConsole.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 = DicContext.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;

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

                    if (inexactPositioning)
                    {
                        DicConsole.
                        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)
                    {
                        DicConsole.
                        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);
                    }

                    DicConsole.WriteLine();
                    DicConsole.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);

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

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

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

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

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

                            int?discOffset = offsetBytes - driveOffset;

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

            dev.Close();
        }
Esempio n. 8
0
        /// <summary>Starts dumping with the stablished fields and autodetecting the device type</summary>
        public void Start()
        {
            // Open master database
            _ctx = DicContext.Create(Settings.Settings.MasterDbPath);

            // Search for device in master database
            _dbDev = _ctx.Devices.FirstOrDefault(d => d.Manufacturer == _dev.Manufacturer && d.Model == _dev.Model &&
                                                 d.Revision == _dev.Revision);

            if (_dbDev is null)
            {
                _dumpLog.WriteLine("Device not in database, please create a device report and attach it to a Github issue.");

                UpdateStatus?.
                Invoke("Device not in database, please create a device report and attach it to a Github issue.");
            }
            else
            {
                _dumpLog.WriteLine($"Device in database since {_dbDev.LastSynchronized}.");
                UpdateStatus?.Invoke($"Device in database since {_dbDev.LastSynchronized}.");

                if (_dbDev.OptimalMultipleSectorsRead > 0)
                {
                    _maximumReadable = (uint)_dbDev.OptimalMultipleSectorsRead;
                }
            }

            if (_dev.IsUsb &&
                _dev.UsbVendorId == 0x054C &&
                (_dev.UsbProductId == 0x01C8 || _dev.UsbProductId == 0x01C9 || _dev.UsbProductId == 0x02D2))
            {
                PlayStationPortable();
            }
            else
            {
                switch (_dev.Type)
                {
                case DeviceType.ATA:
                    Ata();

                    break;

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

                    break;

                case DeviceType.NVMe:
                    NVMe();

                    break;

                case DeviceType.ATAPI:
                case DeviceType.SCSI:
                    Scsi();

                    break;

                default:
                    _dumpLog.WriteLine("Unknown device type.");
                    _dumpLog.Close();
                    StoppingErrorMessage?.Invoke("Unknown device type.");

                    return;
                }
            }

            _dumpLog.Close();

            if (_resume == null ||
                !_doResume)
            {
                return;
            }

            _resume.LastWriteDate = DateTime.UtcNow;
            _resume.BadBlocks.Sort();

            if (File.Exists(_outputPrefix + ".resume.xml"))
            {
                File.Delete(_outputPrefix + ".resume.xml");
            }

            var fs = new FileStream(_outputPrefix + ".resume.xml", FileMode.Create, FileAccess.ReadWrite);
            var xs = new XmlSerializer(_resume.GetType());

            xs.Serialize(fs, _resume);
            fs.Close();
        }
Esempio n. 9
0
        public override int Invoke(IEnumerable <string> arguments)
        {
            List <string> extra = Options.Parse(arguments);

            if (showHelp)
            {
                Options.WriteOptionDescriptions(CommandSet.Out);
                return((int)ErrorNumber.HelpRequested);
            }

            MainClass.PrintCopyright();
            if (MainClass.Debug)
            {
                DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
            }
            if (MainClass.Verbose)
            {
                DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
            }

            if (extra.Count > 0)
            {
                DicConsole.ErrorWriteLine("Too many arguments.");
                return((int)ErrorNumber.UnexpectedArgumentCount);
            }

            DicContext ctx = DicContext.Create(Settings.Settings.LocalDbPath);

            if (!ctx.Commands.Any() && !ctx.Filesystems.Any() && !ctx.Filters.Any() && !ctx.MediaFormats.Any() &&
                !ctx.Medias.Any() && !ctx.Partitions.Any() && !ctx.SeenDevices.Any())
            {
                DicConsole.WriteLine("There are no statistics.");
                return((int)ErrorNumber.NothingFound);
            }

            bool thereAreStats = false;

            if (ctx.Commands.Any())
            {
                DicConsole.WriteLine("Commands statistics");
                DicConsole.WriteLine("===================");

                foreach (string command in ctx.Commands.OrderBy(c => c.Name).Select(c => c.Name).Distinct())
                {
                    ulong count = ctx.Commands.Where(c => c.Name == command && c.Synchronized).Select(c => c.Count)
                                  .FirstOrDefault();
                    count += (ulong)ctx.Commands.LongCount(c => c.Name == command && !c.Synchronized);

                    if (count == 0)
                    {
                        continue;
                    }

                    DicConsole.WriteLine("You have called the {0} command {1} times.", command, count);
                    thereAreStats = true;
                }

                DicConsole.WriteLine();
            }

            if (ctx.Filters.Any())
            {
                DicConsole.WriteLine("Filters statistics");
                DicConsole.WriteLine("==================");

                foreach (string filter in ctx.Filters.OrderBy(c => c.Name).Select(c => c.Name).Distinct())
                {
                    ulong count = ctx.Filters.Where(c => c.Name == filter && c.Synchronized).Select(c => c.Count)
                                  .FirstOrDefault();
                    count += (ulong)ctx.Filters.LongCount(c => c.Name == filter && !c.Synchronized);

                    if (count == 0)
                    {
                        continue;
                    }

                    DicConsole.WriteLine("Filter {0} has been found {1} times.", filter, count);
                    thereAreStats = true;
                }

                DicConsole.WriteLine();
            }

            if (ctx.MediaFormats.Any())
            {
                DicConsole.WriteLine("Media image statistics");
                DicConsole.WriteLine("======================");

                foreach (string format in ctx.MediaFormats.OrderBy(c => c.Name).Select(c => c.Name).Distinct())
                {
                    ulong count = ctx.MediaFormats.Where(c => c.Name == format && c.Synchronized).Select(c => c.Count)
                                  .FirstOrDefault();
                    count += (ulong)ctx.MediaFormats.LongCount(c => c.Name == format && !c.Synchronized);

                    if (count == 0)
                    {
                        continue;
                    }

                    DicConsole.WriteLine("Format {0} has been found {1} times.", format, count);
                    thereAreStats = true;
                }

                DicConsole.WriteLine();
            }

            if (ctx.Partitions.Any())
            {
                DicConsole.WriteLine("Partition statistics");
                DicConsole.WriteLine("====================");

                foreach (string partition in ctx.Partitions.OrderBy(c => c.Name).Select(c => c.Name).Distinct())
                {
                    ulong count = ctx.Partitions.Where(c => c.Name == partition && c.Synchronized).Select(c => c.Count)
                                  .FirstOrDefault();
                    count += (ulong)ctx.Partitions.LongCount(c => c.Name == partition && !c.Synchronized);

                    if (count == 0)
                    {
                        continue;
                    }

                    DicConsole.WriteLine("Partitioning scheme {0} has been found {1} times.", partition, count);
                    thereAreStats = true;
                }

                DicConsole.WriteLine();
            }

            if (ctx.Filesystems.Any())
            {
                DicConsole.WriteLine("Filesystem statistics");
                DicConsole.WriteLine("=====================");

                foreach (string filesystem in ctx.Filesystems.OrderBy(c => c.Name).Select(c => c.Name).Distinct())
                {
                    ulong count = ctx.Filesystems.Where(c => c.Name == filesystem && c.Synchronized)
                                  .Select(c => c.Count).FirstOrDefault();
                    count += (ulong)ctx.Filesystems.LongCount(c => c.Name == filesystem && !c.Synchronized);

                    if (count == 0)
                    {
                        continue;
                    }

                    DicConsole.WriteLine("Filesystem {0} has been found {1} times.", filesystem, count);
                    thereAreStats = true;
                }

                DicConsole.WriteLine();
            }

            if (ctx.SeenDevices.Any())
            {
                DicConsole.WriteLine("Device statistics");
                DicConsole.WriteLine("=================");

                foreach (DeviceStat ds in ctx.SeenDevices.OrderBy(ds => ds.Manufacturer).ThenBy(ds => ds.Model)
                         .ThenBy(ds => ds.Revision).ThenBy(ds => ds.Bus))
                {
                    DicConsole
                    .WriteLine("Device model {0}, manufactured by {1}, with revision {2} and attached via {3}.",
                               ds.Model, ds.Manufacturer, ds.Revision, ds.Bus);
                }

                DicConsole.WriteLine();
                thereAreStats = true;
            }

            if (ctx.Medias.Any())
            {
                DicConsole.WriteLine("Media statistics");
                DicConsole.WriteLine("================");

                foreach (string media in ctx.Medias.OrderBy(ms => ms.Type).Select(ms => ms.Type).Distinct())
                {
                    ulong count = ctx.Medias.Where(c => c.Type == media && c.Synchronized && c.Real)
                                  .Select(c => c.Count).FirstOrDefault();
                    count += (ulong)ctx.Medias.LongCount(c => c.Type == media && !c.Synchronized && c.Real);

                    if (count > 0)
                    {
                        DicConsole.WriteLine("Media type {0} has been found {1} times in a real device.", media, count);
                        thereAreStats = true;
                    }

                    count = ctx.Medias.Where(c => c.Type == media && c.Synchronized && !c.Real).Select(c => c.Count)
                            .FirstOrDefault();
                    count += (ulong)ctx.Medias.LongCount(c => c.Type == media && !c.Synchronized && !c.Real);

                    if (count == 0)
                    {
                        continue;
                    }

                    DicConsole.WriteLine("Media type {0} has been found {1} times in a media image.", media, count);
                    thereAreStats = true;
                }

                DicConsole.WriteLine();
            }

            if (!thereAreStats)
            {
                DicConsole.WriteLine("There are no statistics.");
            }
            return((int)ErrorNumber.NoError);
        }