private void PostDebugReport(TabletReference tablet, IDeviceReport report) { if (report != null && tablet != null) { DeviceReport?.Invoke(this, new DebugReportData(tablet, report)); } }
private void DebugReportHandler(object _, IDeviceReport report) { if (report != null) { DeviceReport?.Invoke(this, new RpcData(report)); } }
public Device(DeviceReport device, ProviderReport providerReport, DeviceIoType type) : this() { Title = device.DeviceName; ProviderName = providerReport.ProviderDescriptor.ProviderName; DeviceHandle = device.DeviceDescriptor.DeviceHandle; DeviceNumber = device.DeviceDescriptor.DeviceInstance; DeviceBindingMenu = GetDeviceBindingMenu(device.Nodes, type); }
public Device(DeviceReport device, ProviderReport providerReport, List <DeviceBindingNode> deviceBindingMenu) : this() { Title = device.DeviceName; ProviderName = providerReport.ProviderDescriptor.ProviderName; DeviceHandle = device.DeviceDescriptor.DeviceHandle; DeviceNumber = device.DeviceDescriptor.DeviceInstance; DeviceBindingMenu = deviceBindingMenu; IsCache = false; }
public T52dBody(string bootLoader, string version, string codeName, string incremental, string fingerprint, string bootId, string androidId, string baseBand, string innerVersion) : base() { var report = new DeviceReport(bootLoader, version, codeName, incremental, fingerprint, bootId, androidId, baseBand, innerVersion); PutProtoNode(report); }
/// <summary> /// Submits a device report /// </summary> /// <param name="report">Device report</param> public static void SubmitReport(DeviceReport report) { Thread submitThread = new Thread(() => { try { #if DEBUG System.Console.WriteLine("Uploading device report"); #else DiscImageChef.Console.DicConsole.DebugWriteLine("Submit stats", "Uploading device report"); #endif MemoryStream xmlStream = new MemoryStream(); XmlSerializer xmlSer = new XmlSerializer(typeof(DeviceReport)); xmlSer.Serialize(xmlStream, report); xmlStream.Seek(0, SeekOrigin.Begin); WebRequest request = WebRequest.Create("http://discimagechef.claunia.com/api/uploadreport"); ((HttpWebRequest)request).UserAgent = $"DiscImageChef {typeof(Version).Assembly.GetName().Version}"; request.Method = "POST"; request.ContentLength = xmlStream.Length; request.ContentType = "application/xml"; Stream reqStream = request.GetRequestStream(); xmlStream.CopyTo(reqStream); reqStream.Close(); WebResponse response = request.GetResponse(); if (((HttpWebResponse)response).StatusCode != HttpStatusCode.OK) { return; } Stream data = response.GetResponseStream(); StreamReader reader = new StreamReader(data ?? throw new InvalidOperationException()); reader.ReadToEnd(); data.Close(); response.Close(); xmlStream.Close(); } catch (WebException) { // Can't connect to the server, do nothing } // ReSharper disable once RedundantCatchClause catch { #if DEBUG throw; #endif } }); submitThread.Start(); }
protected override void OnConnected() { base.OnConnected(); Instance.Message += (sender, e) => Application.Instance.AsyncInvoke(() => Message?.Invoke(sender, e)); Instance.DeviceReport += (sender, e) => Application.Instance.AsyncInvoke(() => DeviceReport?.Invoke(sender, e)); Instance.TabletsChanged += (sender, e) => Application.Instance.AsyncInvoke(() => TabletsChanged?.Invoke(sender, e)); }
/// <summary> /// The create automatically. /// </summary> /// <returns> /// The <see cref="bool"/>. /// </returns> public static bool IsProjectCreated() { Log.Enter(typeof(Project), MethodBase.GetCurrentMethod().Name); bool result = ProgramFunctions.IsMenuAvailable(); result &= DtmFunctions.IsMenuAvailable(); result &= AdditionalFunctions.IsMenuAvailable(); result &= DeviceReport.IsMenuAvailable(); System.Threading.Thread.Sleep(10000); return(result); }
private async Task RegisterDevice(string name, string address, string group) { var device = new DeviceReport() { Address = address, Name = name, Group = group }; var deviceFacade = new DeviceFacade(); await deviceFacade.RegisterDevice(device); }
public async Task ReportStatus(DeviceReport device) { var targetUri = new Uri(baseUrl, $"api/spot/{device.Group}/{device.Address}"); using (var client = new HttpClient()) using (HttpResponseMessage res = await client.GetAsync(targetUri)) using (HttpContent content = res.Content) { var data = await content.ReadAsStringAsync(); } }
public T144Body(string androidId, DeviceReport deviceReport, string osType, string osVersion, NetworkType networkType, string networkDetail, string apnName, bool isNewInstall, bool isGuidAvaliable, bool isGuidChanged, byte[] guid, uint guidFlag, string deviceModel, string deviceBrand) { _tlv109 = new Tlv(0x0109, new T109Body(androidId)); _tlv16e = new Tlv(0x016e, new T16eBody(deviceModel)); _tlv52d = new Tlv(0x052d, new T52dBody(deviceReport)); _tlv124 = new Tlv(0x0124, new T124Body(osType, osVersion, networkType, networkDetail, apnName)); _tlv128 = new Tlv(0x0128, new T128Body(isNewInstall, isGuidAvaliable, isGuidChanged, guid, guidFlag, deviceModel, deviceBrand)); PutT144Body(); }
public HttpResponseMessage UploadReport() { HttpResponseMessage response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK }; try { DeviceReport newReport = new DeviceReport(); HttpRequest request = HttpContext.Current.Request; XmlSerializer xs = new XmlSerializer(newReport.GetType()); newReport = (DeviceReport)xs.Deserialize(request.InputStream); if (newReport == null) { response.Content = new StringContent("notstats", Encoding.UTF8, "text/plain"); return(response); } Random rng = new Random(); string filename = $"NewReport_{DateTime.UtcNow:yyyyMMddHHmmssfff}_{rng.Next()}.xml"; while (File.Exists(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(), "Upload", filename))) { filename = $"NewReport_{DateTime.UtcNow:yyyyMMddHHmmssfff}_{rng.Next()}.xml"; } FileStream newFile = new FileStream(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(), "Upload", filename), FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None); xs.Serialize(newFile, newReport); newFile.Close(); response.Content = new StringContent("ok", Encoding.UTF8, "text/plain"); return(response); } // ReSharper disable once RedundantCatchClause catch { #if DEBUG throw; #else response.Content = new StringContent("error", System.Text.Encoding.UTF8, "text/plain"); return(response); #endif } }
public DeviceReport GetOutputReport() { var deviceReport = new DeviceReport { DeviceName = String.Format("T1 {0}", Title), DeviceDescriptor = new DeviceDescriptor { DeviceHandle = Handle, DeviceInstance = 0 } }; deviceReport.Nodes = GetReportNodes(); return(deviceReport); }
public DeviceReport GetDeviceReport() { var report = new DeviceReport { DeviceName = String.Format("ViGEm {0} Controller {1}", deviceClassDescriptor.classHumanName, (deviceId + 1)), DeviceDescriptor = new DeviceDescriptor { DeviceHandle = deviceClassDescriptor.classIdentifier, DeviceInstance = deviceId } }; report.Nodes.Add(GetAxisReport()); report.Nodes.Add(GetButtonReport()); report.Nodes.Add(GetPovReport()); return(report); }
public DeviceReport GetInputDeviceReport(DeviceDescriptor deviceDescriptor) { var deviceReport = new DeviceReport { DeviceDescriptor = _spaceMouseProDescriptor, DeviceName = "SpaceMouse Pro" }; // ----- Axes ----- var axisInfo = new DeviceReportNode { Title = "Axes" }; for (var i = 0; i < 6; i++) { var bd = new BindingDescriptor { Index = i, Type = BindingType.Axis }; axisInfo.Bindings.Add(GetInputBindingReport(deviceDescriptor, bd)); } deviceReport.Nodes.Add(axisInfo); // ----- Buttons ----- var buttonInfo = new DeviceReportNode { Title = "Buttons" }; foreach (var button in _buttonNames) { var bd = new BindingDescriptor { Index = button.Key, Type = BindingType.Button }; buttonInfo.Bindings.Add(GetInputBindingReport(deviceDescriptor, bd)); } deviceReport.Nodes.Add(buttonInfo); return(deviceReport); }
private bool BuildDeviceReport(ServiceAgent serviceAgent, out DeviceReport deviceReport, out DescriptorMessage requestDescriptor) { requestDescriptor = _udpManager.RequestDescriptor(serviceAgent); if (requestDescriptor == null || !MessageBase.MessageType.Descriptor.Equals(requestDescriptor.Type)) { deviceReport = null; return(false); } var deviceReportNodes = new List <DeviceReportNode>(); if (requestDescriptor.Buttons.Count > 0) { deviceReportNodes.Add(BuildOutputNodes("Buttons", BindingCategory.Momentary, requestDescriptor.Buttons)); } if (requestDescriptor.Axes.Count > 0) { deviceReportNodes.Add(BuildOutputNodes("Axes", BindingCategory.Signed, requestDescriptor.Axes)); } if (requestDescriptor.Deltas.Count > 0) { deviceReportNodes.Add(BuildOutputNodes("Deltas", BindingCategory.Delta, requestDescriptor.Deltas)); } if (requestDescriptor.Events.Count > 0) { deviceReportNodes.Add(BuildOutputNodes("Events", BindingCategory.Event, requestDescriptor.Events)); } var descriptor = new DeviceDescriptor() { DeviceHandle = serviceAgent.Hostname, DeviceInstance = 0 // Unused }; deviceReport = new DeviceReport() { DeviceName = serviceAgent.Hostname, DeviceDescriptor = descriptor, Nodes = deviceReportNodes }; return(true); }
public DeviceReport GetInputDeviceReport(DeviceDescriptor deviceDescriptor) { if (!_connectedInputDevices.TryGetValue(deviceDescriptor.DeviceHandle, out var deviceInstances) || deviceDescriptor.DeviceInstance >= deviceInstances.Count) { return(null); } var devId = deviceInstances[deviceDescriptor.DeviceInstance]; var infoIn = MidiIn.DeviceInfo(devId); var deviceReport = new DeviceReport { DeviceDescriptor = deviceDescriptor, DeviceName = infoIn.ProductName }; deviceReport.Nodes = _inputDeviceReportTemplate.Nodes; return(deviceReport); }
public T52d(string bootLoader, string version, string codeName, string incremental, string fingerprint, string bootId, string androidId, string baseBand, string innerVersion) : base() { DeviceReport report = new DeviceReport { Bootloader = Encoding.UTF8.GetBytes(bootLoader), Version = Encoding.UTF8.GetBytes(version), CodeName = Encoding.UTF8.GetBytes(codeName), Incremental = Encoding.UTF8.GetBytes(incremental), Fingerprint = Encoding.UTF8.GetBytes(fingerprint), BootId = Encoding.UTF8.GetBytes(bootId), AndroidId = Encoding.UTF8.GetBytes(androidId), BaseBand = Encoding.UTF8.GetBytes(baseBand), InnerVersion = Encoding.UTF8.GetBytes(innerVersion) }; MemoryStream stream = new MemoryStream(); Serializer.Serialize(stream, report); _deviceReportInfo = stream.ToArray(); PackGeneric(); }
protected void Page_Load(object sender, EventArgs e) { try { string manufacturer = Request.QueryString["manufacturer"]; string model = Request.QueryString["model"]; string revision = Request.QueryString["revision"]; // Strip non-ascii, strip slashes and question marks if (manufacturer != null) { manufacturer = Encoding .ASCII.GetString(Encoding.Convert(Encoding.UTF8, Encoding.ASCII, Encoding.UTF8.GetBytes(manufacturer))).Replace('/', '_') .Replace('\\', '_').Replace('?', '_'); } if (model != null) { model = Encoding .ASCII.GetString(Encoding.Convert(Encoding.UTF8, Encoding.ASCII, Encoding.UTF8.GetBytes(model))) .Replace('/', '_').Replace('\\', '_').Replace('?', '_'); } if (revision != null) { revision = Encoding .ASCII.GetString(Encoding.Convert(Encoding.UTF8, Encoding.ASCII, Encoding.UTF8.GetBytes(revision))).Replace('/', '_') .Replace('\\', '_').Replace('?', '_'); } string xmlFile = null; if (!string.IsNullOrWhiteSpace(manufacturer) && !string.IsNullOrWhiteSpace(model) && !string.IsNullOrWhiteSpace(revision)) { xmlFile = manufacturer + "_" + model + "_" + revision + ".xml"; } else if (!string.IsNullOrWhiteSpace(manufacturer) && !string.IsNullOrWhiteSpace(model)) { xmlFile = manufacturer + "_" + model + ".xml"; } else if (!string.IsNullOrWhiteSpace(model) && !string.IsNullOrWhiteSpace(revision)) { xmlFile = model + "_" + revision + ".xml"; } else if (!string.IsNullOrWhiteSpace(model)) { xmlFile = model + ".xml"; } if (xmlFile == null || !File.Exists(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(), "Reports", xmlFile))) { content.InnerHtml = "<b>Could not find the specified report</b>"; return; } lblManufacturer.Text = Request.QueryString["manufacturer"]; lblModel.Text = Request.QueryString["model"]; lblRevision.Text = Request.QueryString["revision"]; DeviceReport report = new DeviceReport(); XmlSerializer xs = new XmlSerializer(report.GetType()); StreamReader sr = new StreamReader(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(), "Reports", xmlFile)); report = (DeviceReport)xs.Deserialize(sr); sr.Close(); if (report.USB != null) { GetUsbDescriptions(report.USB.VendorID, report.USB.ProductID, out string usbVendorDescription, out string usbProductDescription); lblUsbManufacturer.Text = HttpUtility.HtmlEncode(report.USB.Manufacturer); lblUsbProduct.Text = HttpUtility.HtmlEncode(report.USB.Product); lblUsbVendor.Text = $"0x{report.USB.VendorID:x4}"; if (usbVendorDescription != null) { lblUsbVendorDescription.Text = $"({HttpUtility.HtmlEncode(usbVendorDescription)})"; } lblUsbProductId.Text = $"0x{report.USB.ProductID:x4}"; if (usbProductDescription != null) { lblUsbProductDescription.Text = $"({HttpUtility.HtmlEncode(usbProductDescription)})"; } } else { divUsb.Visible = false; } if (report.FireWire != null) { lblFirewireManufacturer.Text = HttpUtility.HtmlEncode(report.FireWire.Manufacturer); lblFirewireProduct.Text = HttpUtility.HtmlEncode(report.FireWire.Product); lblFirewireVendor.Text = $"0x{report.FireWire.VendorID:x8}"; lblFirewireProductId.Text = $"0x{report.FireWire.ProductID:x8}"; } else { divFirewire.Visible = false; } if (report.PCMCIA != null) { lblPcmciaManufacturer.Text = HttpUtility.HtmlEncode(report.PCMCIA.Manufacturer); lblPcmciaProduct.Text = HttpUtility.HtmlEncode(report.PCMCIA.ProductName); lblPcmciaManufacturerCode.Text = $"0x{report.PCMCIA.ManufacturerCode:x4}"; lblPcmciaCardCode.Text = $"0x{report.PCMCIA.CardCode:x4}"; lblPcmciaCompliance.Text = HttpUtility.HtmlEncode(report.PCMCIA.Compliance); Tuple[] tuples = CIS.GetTuples(report.PCMCIA.CIS); if (tuples != null) { Dictionary <string, string> decodedTuples = new Dictionary <string, string>(); foreach (Tuple tuple in tuples) { switch (tuple.Code) { case TupleCodes.CISTPL_NULL: case TupleCodes.CISTPL_END: case TupleCodes.CISTPL_MANFID: case TupleCodes.CISTPL_VERS_1: break; case TupleCodes.CISTPL_DEVICEGEO: case TupleCodes.CISTPL_DEVICEGEO_A: DeviceGeometryTuple geom = CIS.DecodeDeviceGeometryTuple(tuple.Data); if (geom?.Geometries != null) { foreach (DeviceGeometry geometry in geom.Geometries) { decodedTuples.Add("Device width", $"{(1 << (geometry.CardInterface - 1)) * 8} bits"); decodedTuples.Add("Erase block", $"{(1 << (geometry.EraseBlockSize - 1)) * (1 << (geometry.Interleaving - 1))} bytes"); decodedTuples.Add("Read block", $"{(1 << (geometry.ReadBlockSize - 1)) * (1 << (geometry.Interleaving - 1))} bytes"); decodedTuples.Add("Write block", $"{(1 << (geometry.WriteBlockSize - 1)) * (1 << (geometry.Interleaving - 1))} bytes"); decodedTuples.Add("Partition alignment", $"{(1 << (geometry.EraseBlockSize - 1)) * (1 << (geometry.Interleaving - 1)) * (1 << (geometry.Partitions - 1))} bytes"); } } break; case TupleCodes.CISTPL_ALTSTR: case TupleCodes.CISTPL_BAR: case TupleCodes.CISTPL_BATTERY: case TupleCodes.CISTPL_BYTEORDER: case TupleCodes.CISTPL_CFTABLE_ENTRY: case TupleCodes.CISTPL_CFTABLE_ENTRY_CB: case TupleCodes.CISTPL_CHECKSUM: case TupleCodes.CISTPL_CONFIG: case TupleCodes.CISTPL_CONFIG_CB: case TupleCodes.CISTPL_DATE: case TupleCodes.CISTPL_DEVICE: case TupleCodes.CISTPL_DEVICE_A: case TupleCodes.CISTPL_DEVICE_OA: case TupleCodes.CISTPL_DEVICE_OC: case TupleCodes.CISTPL_EXTDEVIC: case TupleCodes.CISTPL_FORMAT: case TupleCodes.CISTPL_FORMAT_A: case TupleCodes.CISTPL_FUNCE: case TupleCodes.CISTPL_FUNCID: case TupleCodes.CISTPL_GEOMETRY: case TupleCodes.CISTPL_INDIRECT: case TupleCodes.CISTPL_JEDEC_A: case TupleCodes.CISTPL_JEDEC_C: case TupleCodes.CISTPL_LINKTARGET: case TupleCodes.CISTPL_LONGLINK_A: case TupleCodes.CISTPL_LONGLINK_C: case TupleCodes.CISTPL_LONGLINK_CB: case TupleCodes.CISTPL_LONGLINK_MFC: case TupleCodes.CISTPL_NO_LINK: case TupleCodes.CISTPL_ORG: case TupleCodes.CISTPL_PWR_MGMNT: case TupleCodes.CISTPL_SPCL: case TupleCodes.CISTPL_SWIL: case TupleCodes.CISTPL_VERS_2: decodedTuples.Add("Undecoded tuple ID", tuple.Code.ToString()); break; default: decodedTuples.Add("Unknown tuple ID", $"0x{(byte)tuple.Code:X2}"); break; } } if (decodedTuples.Count > 0) { repPcmciaTuples.DataSource = decodedTuples; repPcmciaTuples.DataBind(); } else { repPcmciaTuples.Visible = false; } } else { repPcmciaTuples.Visible = false; } } else { divPcmcia.Visible = false; } bool removable = true; testedMediaType[] testedMedia = null; bool ata = false; bool atapi = false; bool sscMedia = false; if (report.ATA != null || report.ATAPI != null) { ata = true; List <string> ataOneValue = new List <string>(); Dictionary <string, string> ataTwoValue = new Dictionary <string, string>(); ataType ataReport; if (report.ATAPI != null) { lblAtapi.Text = "PI"; ataReport = report.ATAPI; atapi = true; } else { ataReport = report.ATA; } bool cfa = report.CompactFlashSpecified && report.CompactFlash; if (atapi && !cfa) { lblAtaDeviceType.Text = "ATAPI device"; } else if (!atapi && cfa) { lblAtaDeviceType.Text = "CompactFlash device"; } else { lblAtaDeviceType.Text = "ATA device"; } Ata.Report(ataReport, cfa, atapi, ref removable, ref ataOneValue, ref ataTwoValue, ref testedMedia); repAtaOne.DataSource = ataOneValue; repAtaOne.DataBind(); repAtaTwo.DataSource = ataTwoValue; repAtaTwo.DataBind(); } else { divAta.Visible = false; } if (report.SCSI != null) { List <string> scsiOneValue = new List <string>(); Dictionary <string, string> modePages = new Dictionary <string, string>(); Dictionary <string, string> evpdPages = new Dictionary <string, string>(); lblScsiVendor.Text = VendorString.Prettify(report.SCSI.Inquiry.VendorIdentification) != report.SCSI.Inquiry.VendorIdentification ? $"{report.SCSI.Inquiry.VendorIdentification} ({VendorString.Prettify(report.SCSI.Inquiry.VendorIdentification)})" : report.SCSI.Inquiry.VendorIdentification; lblScsiProduct.Text = report.SCSI.Inquiry.ProductIdentification; lblScsiRevision.Text = report.SCSI.Inquiry.ProductRevisionLevel; scsiOneValue.AddRange(ScsiInquiry.Report(report.SCSI.Inquiry)); if (report.SCSI.SupportsModeSense6) { scsiOneValue.Add("Device supports MODE SENSE (6)"); } if (report.SCSI.SupportsModeSense10) { scsiOneValue.Add("Device supports MODE SENSE (10)"); } if (report.SCSI.SupportsModeSubpages) { scsiOneValue.Add("Device supports MODE SENSE subpages"); } if (report.SCSI.ModeSense != null) { ScsiModeSense.Report(report.SCSI.ModeSense, report.SCSI.Inquiry.VendorIdentification, report.SCSI.Inquiry.PeripheralDeviceType, ref scsiOneValue, ref modePages); } if (modePages.Count > 0) { repModeSense.DataSource = modePages; repModeSense.DataBind(); } else { divScsiModeSense.Visible = false; } if (report.SCSI.EVPDPages != null) { ScsiEvpd.Report(report.SCSI.EVPDPages, report.SCSI.Inquiry.VendorIdentification, ref evpdPages); } if (evpdPages.Count > 0) { repEvpd.DataSource = evpdPages; repEvpd.DataBind(); } else { divScsiEvpd.Visible = false; } divScsiMmcMode.Visible = false; divScsiMmcFeatures.Visible = false; divScsiSsc.Visible = false; if (report.SCSI.MultiMediaDevice != null) { testedMedia = report.SCSI.MultiMediaDevice.TestedMedia; if (report.SCSI.MultiMediaDevice.ModeSense2A != null) { List <string> mmcModeOneValue = new List <string>(); ScsiMmcMode.Report(report.SCSI.MultiMediaDevice.ModeSense2A, ref mmcModeOneValue); if (mmcModeOneValue.Count > 0) { divScsiMmcMode.Visible = true; repScsiMmcMode.DataSource = mmcModeOneValue; repScsiMmcMode.DataBind(); } } if (report.SCSI.MultiMediaDevice.Features != null) { List <string> mmcFeaturesOneValue = new List <string>(); ScsiMmcFeatures.Report(report.SCSI.MultiMediaDevice.Features, ref mmcFeaturesOneValue); if (mmcFeaturesOneValue.Count > 0) { divScsiMmcFeatures.Visible = true; repScsiMmcFeatures.DataSource = mmcFeaturesOneValue; repScsiMmcFeatures.DataBind(); } } } else if (report.SCSI.SequentialDevice != null) { divScsiSsc.Visible = true; lblScsiSscGranularity.Text = report.SCSI.SequentialDevice.BlockSizeGranularitySpecified ? report.SCSI.SequentialDevice.BlockSizeGranularity.ToString() : "Unspecified"; lblScsiSscMaxBlock.Text = report.SCSI.SequentialDevice.MaxBlockLengthSpecified ? report.SCSI.SequentialDevice.MaxBlockLength.ToString() : "Unspecified"; lblScsiSscMinBlock.Text = report.SCSI.SequentialDevice.MinBlockLengthSpecified ? report.SCSI.SequentialDevice.MinBlockLength.ToString() : "Unspecified"; if (report.SCSI.SequentialDevice.SupportedDensities != null) { repScsiSscDensities.DataSource = report.SCSI.SequentialDevice.SupportedDensities; repScsiSscDensities.DataBind(); } else { repScsiSscDensities.Visible = false; } if (report.SCSI.SequentialDevice.SupportedMediaTypes != null) { repScsiSscMedias.DataSource = report.SCSI.SequentialDevice.SupportedMediaTypes; repScsiSscMedias.DataBind(); } else { repScsiSscMedias.Visible = false; } if (report.SCSI.SequentialDevice.TestedMedia != null) { List <string> mediaOneValue = new List <string>(); SscTestedMedia.Report(report.SCSI.SequentialDevice.TestedMedia, ref mediaOneValue); if (mediaOneValue.Count > 0) { sscMedia = true; repTestedMedia.DataSource = mediaOneValue; repTestedMedia.DataBind(); } else { divTestedMedia.Visible = false; } } else { divTestedMedia.Visible = false; } } else if (report.SCSI.ReadCapabilities != null) { removable = false; scsiOneValue.Add(""); if (report.SCSI.ReadCapabilities.BlocksSpecified && report.SCSI.ReadCapabilities.BlockSizeSpecified) { scsiOneValue .Add($"Device has {report.SCSI.ReadCapabilities.Blocks} blocks of {report.SCSI.ReadCapabilities.BlockSize} bytes each"); if (report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize / 1024 / 1024 > 1000000) { scsiOneValue .Add($"Device size: {report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize} bytes, {report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize / 1000 / 1000 / 1000 / 1000} Tb, {(double)(report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize) / 1024 / 1024 / 1024 / 1024:F2} TiB"); } else if (report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize / 1024 / 1024 > 1000) { scsiOneValue .Add($"Device size: {report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize} bytes, {report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize / 1000 / 1000 / 1000} Gb, {(double)(report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize) / 1024 / 1024 / 1024:F2} GiB"); } else { scsiOneValue .Add($"Device size: {report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize} bytes, {report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize / 1000 / 1000} Mb, {(double)(report.SCSI.ReadCapabilities.Blocks * report.SCSI.ReadCapabilities.BlockSize) / 1024 / 1024:F2} MiB"); } } if (report.SCSI.ReadCapabilities.MediumTypeSpecified) { scsiOneValue.Add($"Medium type code: {report.SCSI.ReadCapabilities.MediumType:X2}h"); } if (report.SCSI.ReadCapabilities.DensitySpecified) { scsiOneValue.Add($"Density code: {report.SCSI.ReadCapabilities.Density:X2}h"); } if ((report.SCSI.ReadCapabilities.SupportsReadLong || report.SCSI.ReadCapabilities.SupportsReadLong16) && report.SCSI.ReadCapabilities.LongBlockSizeSpecified) { scsiOneValue.Add($"Long block size: {report.SCSI.ReadCapabilities.LongBlockSize} bytes"); } if (report.SCSI.ReadCapabilities.SupportsReadCapacity) { scsiOneValue.Add("Device supports READ CAPACITY (10) command."); } if (report.SCSI.ReadCapabilities.SupportsReadCapacity16) { scsiOneValue.Add("Device supports READ CAPACITY (16) command."); } if (report.SCSI.ReadCapabilities.SupportsRead) { scsiOneValue.Add("Device supports READ (6) command."); } if (report.SCSI.ReadCapabilities.SupportsRead10) { scsiOneValue.Add("Device supports READ (10) command."); } if (report.SCSI.ReadCapabilities.SupportsRead12) { scsiOneValue.Add("Device supports READ (12) command."); } if (report.SCSI.ReadCapabilities.SupportsRead16) { scsiOneValue.Add("Device supports READ (16) command."); } if (report.SCSI.ReadCapabilities.SupportsReadLong) { scsiOneValue.Add("Device supports READ LONG (10) command."); } if (report.SCSI.ReadCapabilities.SupportsReadLong16) { scsiOneValue.Add("Device supports READ LONG (16) command."); } } else { testedMedia = report.SCSI.RemovableMedias; } repScsi.DataSource = scsiOneValue; repScsi.DataBind(); } else { divScsi.Visible = false; } if (report.MultiMediaCard != null) { List <string> mmcOneValue = new List <string>(); if (report.MultiMediaCard.CID != null) { mmcOneValue.Add(Decoders.MMC.Decoders.PrettifyCID(report.MultiMediaCard.CID) .Replace("\n", "<br/>")); mmcOneValue.Add(""); } if (report.MultiMediaCard.CSD != null) { mmcOneValue.Add(Decoders.MMC.Decoders.PrettifyCSD(report.MultiMediaCard.CSD) .Replace("\n", "<br/>")); mmcOneValue.Add(""); } if (report.MultiMediaCard.ExtendedCSD != null) { mmcOneValue.Add(Decoders.MMC.Decoders.PrettifyExtendedCSD(report.MultiMediaCard.ExtendedCSD) .Replace("\n", "<br/>")); mmcOneValue.Add(""); } if (report.MultiMediaCard.OCR != null) { mmcOneValue.Add(Decoders.MMC.Decoders.PrettifyCSD(report.MultiMediaCard.OCR) .Replace("\n", "<br/>")); mmcOneValue.Add(""); } repMMC.DataSource = mmcOneValue; repMMC.DataBind(); } else { divMMC.Visible = false; } if (report.SecureDigital != null) { List <string> sdOneValue = new List <string>(); if (report.SecureDigital.CID != null) { sdOneValue.Add(Decoders.SecureDigital.Decoders.PrettifyCID(report.SecureDigital.CID) .Replace("\n", "<br/>")); sdOneValue.Add(""); } if (report.SecureDigital.CSD != null) { sdOneValue.Add(Decoders.SecureDigital.Decoders.PrettifyCSD(report.SecureDigital.CSD) .Replace("\n", "<br/>")); sdOneValue.Add(""); } if (report.SecureDigital.SCR != null) { sdOneValue.Add(Decoders.SecureDigital.Decoders.PrettifySCR(report.SecureDigital.SCR) .Replace("\n", "<br/>")); sdOneValue.Add(""); } if (report.SecureDigital.OCR != null) { sdOneValue.Add(Decoders.SecureDigital.Decoders.PrettifyCSD(report.SecureDigital.OCR) .Replace("\n", "<br/>")); sdOneValue.Add(""); } repSD.DataSource = sdOneValue; repSD.DataBind(); } else { divSD.Visible = false; } if (removable && !sscMedia && testedMedia != null) { List <string> mediaOneValue = new List <string>(); TestedMedia.Report(testedMedia, ata, ref mediaOneValue); if (mediaOneValue.Count > 0) { divTestedMedia.Visible = true; repTestedMedia.DataSource = mediaOneValue; repTestedMedia.DataBind(); } else { divTestedMedia.Visible = false; } } else { divTestedMedia.Visible &= sscMedia; } } catch (Exception) { content.InnerHtml = "<b>Could not load device report</b>"; #if DEBUG throw; #endif } }
public ActionResult Index() { ViewBag.Version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); try { if (System.IO.File.Exists(Path.Combine(_env.ContentRootPath ?? throw new InvalidOperationException(), "Statistics", "Statistics.xml"))) { try { var statistics = new Stats(); var xs = new XmlSerializer(statistics.GetType()); FileStream fs = WaitForFile(Path.Combine(_env.ContentRootPath ?? throw new InvalidOperationException(), "Statistics", "Statistics.xml"), FileMode.Open, FileAccess.Read, FileShare.Read); statistics = (Stats)xs.Deserialize(fs); fs.Close(); StatsConverter.Convert(statistics); System.IO.File.Delete(Path.Combine(_env.ContentRootPath ?? throw new InvalidOperationException(), "Statistics", "Statistics.xml")); } catch (XmlException) { // Do nothing } } if (_ctx.OperatingSystems.Any()) { List <NameValueStats> operatingSystems = new(); foreach (OperatingSystem nvs in _ctx.OperatingSystems) { operatingSystems.Add(new NameValueStats { name = $"{DetectOS.GetPlatformName((PlatformID)Enum.Parse(typeof(PlatformID), nvs.Name), nvs.Version)}{(string.IsNullOrEmpty(nvs.Version) ? "" : " ")}{nvs.Version}", Value = nvs.Count }); } ViewBag.repOperatingSystems = operatingSystems.OrderBy(os => os.name).ToList(); } if (_ctx.Versions.Any()) { List <NameValueStats> versions = new(); foreach (Version nvs in _ctx.Versions) { versions.Add(new NameValueStats { name = nvs.Name == "previous" ? "Previous than 3.4.99.0" : nvs.Name, Value = nvs.Count }); } ViewBag.repVersions = versions.OrderBy(ver => ver.name).ToList(); } if (_ctx.Commands.Any()) { ViewBag.repCommands = _ctx.Commands.OrderBy(c => c.Name).ToList(); } if (_ctx.Filters.Any()) { ViewBag.repFilters = _ctx.Filters.OrderBy(filter => filter.Name).ToList(); } if (_ctx.MediaFormats.Any()) { ViewBag.repMediaImages = _ctx.MediaFormats.OrderBy(filter => filter.Name).ToList(); } if (_ctx.Partitions.Any()) { ViewBag.repPartitions = _ctx.Partitions.OrderBy(filter => filter.Name).ToList(); } if (_ctx.Filesystems.Any()) { ViewBag.repFilesystems = _ctx.Filesystems.OrderBy(filter => filter.Name).ToList(); } if (_ctx.Medias.Any()) { List <MediaItem> realMedia = new(); List <MediaItem> virtualMedia = new(); foreach (Media nvs in _ctx.Medias) { try { (string type, string subType)mediaType = MediaType.MediaTypeToString((CommonTypes.MediaType)Enum.Parse(typeof(CommonTypes.MediaType), nvs.Type)); if (nvs.Real) { realMedia.Add(new MediaItem { Type = mediaType.type, SubType = mediaType.subType, Count = nvs.Count }); } else { virtualMedia.Add(new MediaItem { Type = mediaType.type, SubType = mediaType.subType, Count = nvs.Count }); } } catch { if (nvs.Real) { realMedia.Add(new MediaItem { Type = nvs.Type, SubType = null, Count = nvs.Count }); } else { virtualMedia.Add(new MediaItem { Type = nvs.Type, SubType = null, Count = nvs.Count }); } } } if (realMedia.Count > 0) { ViewBag.repRealMedia = realMedia.OrderBy(media => media.Type).ThenBy(media => media.SubType). ToList(); } if (virtualMedia.Count > 0) { ViewBag.repVirtualMedia = virtualMedia.OrderBy(media => media.Type).ThenBy(media => media.SubType). ToList(); } } if (_ctx.DeviceStats.Any()) { List <DeviceItem> devices = new(); foreach (DeviceStat device in _ctx.DeviceStats.ToList()) { string xmlFile; if (!string.IsNullOrWhiteSpace(device.Manufacturer) && !string.IsNullOrWhiteSpace(device.Model) && !string.IsNullOrWhiteSpace(device.Revision)) { xmlFile = device.Manufacturer + "_" + device.Model + "_" + device.Revision + ".xml"; } else if (!string.IsNullOrWhiteSpace(device.Manufacturer) && !string.IsNullOrWhiteSpace(device.Model)) { xmlFile = device.Manufacturer + "_" + device.Model + ".xml"; } else if (!string.IsNullOrWhiteSpace(device.Model) && !string.IsNullOrWhiteSpace(device.Revision)) { xmlFile = device.Model + "_" + device.Revision + ".xml"; } else { xmlFile = device.Model + ".xml"; } xmlFile = xmlFile.Replace('/', '_').Replace('\\', '_').Replace('?', '_'); if (System.IO.File.Exists(Path.Combine(_env.ContentRootPath, "Reports", xmlFile))) { var deviceReport = new DeviceReport(); var xs = new XmlSerializer(deviceReport.GetType()); FileStream fs = WaitForFile(Path.Combine(_env.ContentRootPath ?? throw new InvalidOperationException(), "Reports", xmlFile), FileMode.Open, FileAccess.Read, FileShare.Read); deviceReport = (DeviceReport)xs.Deserialize(fs); fs.Close(); var deviceReportV2 = new DeviceReportV2(deviceReport); device.Report = _ctx.Devices.Add(new Device(deviceReportV2)).Entity; _ctx.SaveChanges(); System.IO.File. Delete(Path.Combine(_env.ContentRootPath ?? throw new InvalidOperationException(), "Reports", xmlFile)); } devices.Add(new DeviceItem { Manufacturer = device.Manufacturer, Model = device.Model, Revision = device.Revision, Bus = device.Bus, ReportId = device.Report != null && device.Report.Id != 0 ? device.Report.Id : 0 }); } ViewBag.repDevices = devices.OrderBy(device => device.Manufacturer).ThenBy(device => device.Model). ThenBy(device => device.Revision).ThenBy(device => device.Bus).ToList(); } } catch (Exception) { #if DEBUG throw; #endif return(Content("Could not read statistics")); } return(View()); }
public ActionResult Index() { ViewBag.Version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); try { if ( System.IO.File .Exists(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(), "Statistics", "Statistics.xml"))) { try { Stats statistics = new Stats(); XmlSerializer xs = new XmlSerializer(statistics.GetType()); FileStream fs = WaitForFile(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(), "Statistics", "Statistics.xml"), FileMode.Open, FileAccess.Read, FileShare.Read); statistics = (Stats)xs.Deserialize(fs); fs.Close(); StatsConverter.Convert(statistics); System.IO.File .Delete(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(), "Statistics", "Statistics.xml")); } catch (XmlException) { // Do nothing } } if (ctx.OperatingSystems.Any()) { operatingSystems = new List <NameValueStats>(); foreach (OperatingSystem nvs in ctx.OperatingSystems) { operatingSystems.Add(new NameValueStats { name = $"{DetectOS.GetPlatformName((PlatformID)Enum.Parse(typeof(PlatformID), nvs.Name), nvs.Version)}{(string.IsNullOrEmpty(nvs.Version) ? "" : " ")}{nvs.Version}", Value = nvs.Count }); } ViewBag.repOperatingSystems = operatingSystems.OrderBy(os => os.name).ToList(); List <PieSeriesData> osPieData = new List <PieSeriesData>(); decimal totalOsCount = ctx.OperatingSystems.Sum(o => o.Count); foreach (string os in ctx.OperatingSystems.Select(o => o.Name).Distinct().ToList()) { decimal osCount = ctx.OperatingSystems.Where(o => o.Name == os).Sum(o => o.Count); osPieData.Add(new PieSeriesData { Name = DetectOS.GetPlatformName((PlatformID)Enum.Parse(typeof(PlatformID), os)), Y = (double?)(osCount / totalOsCount), Sliced = os == "Linux", Selected = os == "Linux" }); } ViewData["osPieData"] = osPieData; List <PieSeriesData> linuxPieData = new List <PieSeriesData>(); decimal linuxCount = ctx.OperatingSystems.Where(o => o.Name == PlatformID.Linux.ToString()) .Sum(o => o.Count); foreach (OperatingSystem version in ctx.OperatingSystems.Where(o => o.Name == PlatformID.Linux.ToString())) { linuxPieData.Add(new PieSeriesData { Name = $"{DetectOS.GetPlatformName(PlatformID.Linux, version.Version)}{(string.IsNullOrEmpty(version.Version) ? "" : " ")}{version.Version}", Y = (double?)(version.Count / linuxCount) }); } ViewData["linuxPieData"] = linuxPieData; List <PieSeriesData> macosPieData = new List <PieSeriesData>(); decimal macosCount = ctx.OperatingSystems.Where(o => o.Name == PlatformID.MacOSX.ToString()) .Sum(o => o.Count); foreach (OperatingSystem version in ctx.OperatingSystems.Where(o => o.Name == PlatformID.MacOSX.ToString())) { macosPieData.Add(new PieSeriesData { Name = $"{DetectOS.GetPlatformName(PlatformID.MacOSX, version.Version)}{(string.IsNullOrEmpty(version.Version) ? "" : " ")}{version.Version}", Y = (double?)(version.Count / macosCount) }); } ViewData["macosPieData"] = macosPieData; List <PieSeriesData> windowsPieData = new List <PieSeriesData>(); decimal windowsCount = ctx.OperatingSystems.Where(o => o.Name == PlatformID.Win32NT.ToString()) .Sum(o => o.Count); foreach (OperatingSystem version in ctx.OperatingSystems.Where(o => o.Name == PlatformID.Win32NT.ToString())) { windowsPieData.Add(new PieSeriesData { Name = $"{DetectOS.GetPlatformName(PlatformID.Win32NT, version.Version)}{(string.IsNullOrEmpty(version.Version) ? "" : " ")}{version.Version}", Y = (double?)(version.Count / windowsCount) }); } ViewData["windowsPieData"] = windowsPieData; } if (ctx.Versions.Any()) { versions = new List <NameValueStats>(); foreach (Version nvs in ctx.Versions) { versions.Add(new NameValueStats { name = nvs.Value == "previous" ? "Previous than 3.4.99.0" : nvs.Value, Value = nvs.Count }); } ViewBag.repVersions = versions.OrderBy(ver => ver.name).ToList(); decimal totalVersionCount = ctx.Versions.Sum(o => o.Count); ViewData["versionsPieData"] = ctx.Versions.Select(version => new PieSeriesData { Name = version.Value == "previous" ? "Previous than 3.4.99.0" : version.Value, Y = (double?)(version.Count / totalVersionCount), Sliced = version.Value == "previous", Selected = version.Value == "previous" }).ToList(); } if (ctx.Commands.Any()) { ViewBag.repCommands = ctx.Commands.OrderBy(c => c.Name).ToList(); decimal totalCommandCount = ctx.Commands.Sum(o => o.Count); ViewData["commandsPieData"] = ctx .Commands.Select(command => new PieSeriesData { Name = command.Name, Y = (double?)(command.Count / totalCommandCount), Sliced = command.Name == "analyze", Selected = command.Name == "analyze" }).ToList(); } if (ctx.Filters.Any()) { ViewBag.repFilters = ctx.Filters.OrderBy(filter => filter.Name).ToList(); List <PieSeriesData> filtersPieData = new List <PieSeriesData>(); decimal totalFiltersCount = ctx.Filters.Sum(o => o.Count); foreach (Filter filter in ctx.Filters.ToList()) { filtersPieData.Add(new PieSeriesData { Name = filter.Name, Y = (double?)(filter.Count / totalFiltersCount), Sliced = filter.Name == "No filter", Selected = filter.Name == "No filter" }); } ViewData["filtersPieData"] = filtersPieData; } if (ctx.MediaFormats.Any()) { ViewBag.repMediaImages = ctx.MediaFormats.OrderBy(filter => filter.Name).ToList(); List <PieSeriesData> formatsPieData = new List <PieSeriesData>(); decimal totalFormatsCount = ctx.MediaFormats.Sum(o => o.Count); decimal top10FormatCount = 0; foreach (MediaFormat format in ctx.MediaFormats.OrderByDescending(o => o.Count).Take(10)) { top10FormatCount += format.Count; formatsPieData.Add(new PieSeriesData { Name = format.Name, Y = (double?)(format.Count / totalFormatsCount) }); } formatsPieData.Add(new PieSeriesData { Name = "Other", Y = (double?)((totalFormatsCount - top10FormatCount) / totalFormatsCount), Sliced = true, Selected = true }); ViewData["formatsPieData"] = formatsPieData; } if (ctx.Partitions.Any()) { ViewBag.repPartitions = ctx.Partitions.OrderBy(filter => filter.Name).ToList(); List <PieSeriesData> partitionsPieData = new List <PieSeriesData>(); decimal totalPartitionsCount = ctx.Partitions.Sum(o => o.Count); decimal top10PartitionCount = 0; foreach (Partition partition in ctx.Partitions.OrderByDescending(o => o.Count).Take(10)) { top10PartitionCount += partition.Count; partitionsPieData.Add(new PieSeriesData { Name = partition.Name, Y = (double?)(partition.Count / totalPartitionsCount) }); } partitionsPieData.Add(new PieSeriesData { Name = "Other", Y = (double?)((totalPartitionsCount - top10PartitionCount) / totalPartitionsCount), Sliced = true, Selected = true }); ViewData["partitionsPieData"] = partitionsPieData; } if (ctx.Filesystems.Any()) { ViewBag.repFilesystems = ctx.Filesystems.OrderBy(filter => filter.Name).ToList(); List <PieSeriesData> filesystemsPieData = new List <PieSeriesData>(); decimal totalFilesystemsCount = ctx.Filesystems.Sum(o => o.Count); decimal top10FilesystemCount = 0; foreach (Filesystem filesystem in ctx.Filesystems.OrderByDescending(o => o.Count).Take(10)) { top10FilesystemCount += filesystem.Count; filesystemsPieData.Add(new PieSeriesData { Name = filesystem.Name, Y = (double?)(filesystem.Count / totalFilesystemsCount) }); } filesystemsPieData.Add(new PieSeriesData { Name = "Other", Y = (double?)((totalFilesystemsCount - top10FilesystemCount) / totalFilesystemsCount), Sliced = true, Selected = true }); ViewData["filesystemsPieData"] = filesystemsPieData; } if (ctx.Medias.Any()) { realMedia = new List <MediaItem>(); virtualMedia = new List <MediaItem>(); foreach (Media nvs in ctx.Medias) { try { MediaType .MediaTypeToString((CommonTypes.MediaType)Enum.Parse(typeof(CommonTypes.MediaType), nvs.Type), out string type, out string subtype); if (nvs.Real) { realMedia.Add(new MediaItem { Type = type, SubType = subtype, Count = nvs.Count }); } else { virtualMedia.Add(new MediaItem { Type = type, SubType = subtype, Count = nvs.Count }); } } catch { if (nvs.Real) { realMedia.Add(new MediaItem { Type = nvs.Type, SubType = null, Count = nvs.Count }); } else { virtualMedia.Add(new MediaItem { Type = nvs.Type, SubType = null, Count = nvs.Count }); } } } if (realMedia.Count > 0) { ViewBag.repRealMedia = realMedia.OrderBy(media => media.Type).ThenBy(media => media.SubType).ToList(); List <PieSeriesData> realMediaPieData = new List <PieSeriesData>(); decimal totalRealMediaCount = realMedia.Sum(o => o.Count); decimal top10RealMediaCount = 0; foreach (MediaItem realMediaItem in realMedia.OrderByDescending(o => o.Count).Take(10)) { top10RealMediaCount += realMediaItem.Count; realMediaPieData.Add(new PieSeriesData { Name = $"{realMediaItem.Type} ({realMediaItem.SubType})", Y = (double?)(realMediaItem.Count / totalRealMediaCount) }); } realMediaPieData.Add(new PieSeriesData { Name = "Other", Y = (double?)((totalRealMediaCount - top10RealMediaCount) / totalRealMediaCount), Sliced = true, Selected = true }); ViewData["realMediaPieData"] = realMediaPieData; } if (virtualMedia.Count > 0) { ViewBag.repVirtualMedia = virtualMedia.OrderBy(media => media.Type).ThenBy(media => media.SubType).ToList(); List <PieSeriesData> virtualMediaPieData = new List <PieSeriesData>(); decimal totalVirtualMediaCount = virtualMedia.Sum(o => o.Count); decimal top10VirtualMediaCount = 0; foreach (MediaItem virtualMediaItem in virtualMedia.OrderByDescending(o => o.Count).Take(10)) { top10VirtualMediaCount += virtualMediaItem.Count; virtualMediaPieData.Add(new PieSeriesData { Name = $"{virtualMediaItem.Type} ({virtualMediaItem.SubType})", Y = (double?)(virtualMediaItem.Count / totalVirtualMediaCount) }); } virtualMediaPieData.Add(new PieSeriesData { Name = "Other", Y = (double?) ((totalVirtualMediaCount - top10VirtualMediaCount) / totalVirtualMediaCount), Sliced = true, Selected = true }); ViewData["virtualMediaPieData"] = virtualMediaPieData; } } if (ctx.DeviceStats.Any()) { devices = new List <DeviceItem>(); foreach (DeviceStat device in ctx.DeviceStats.ToList()) { string xmlFile; if (!string.IsNullOrWhiteSpace(device.Manufacturer) && !string.IsNullOrWhiteSpace(device.Model) && !string.IsNullOrWhiteSpace(device.Revision)) { xmlFile = device.Manufacturer + "_" + device.Model + "_" + device.Revision + ".xml"; } else if (!string.IsNullOrWhiteSpace(device.Manufacturer) && !string.IsNullOrWhiteSpace(device.Model)) { xmlFile = device.Manufacturer + "_" + device.Model + ".xml"; } else if (!string.IsNullOrWhiteSpace(device.Model) && !string.IsNullOrWhiteSpace(device.Revision)) { xmlFile = device.Model + "_" + device.Revision + ".xml"; } else { xmlFile = device.Model + ".xml"; } xmlFile = xmlFile.Replace('/', '_').Replace('\\', '_').Replace('?', '_'); if (System.IO.File.Exists(Path.Combine(HostingEnvironment.MapPath("~"), "Reports", xmlFile))) { DeviceReport deviceReport = new DeviceReport(); XmlSerializer xs = new XmlSerializer(deviceReport.GetType()); FileStream fs = WaitForFile(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(), "Reports", xmlFile), FileMode.Open, FileAccess.Read, FileShare.Read); deviceReport = (DeviceReport)xs.Deserialize(fs); fs.Close(); DeviceReportV2 deviceReportV2 = new DeviceReportV2(deviceReport); device.Report = ctx.Devices.Add(new Device(deviceReportV2)); ctx.SaveChanges(); System.IO.File .Delete(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(), "Reports", xmlFile)); } devices.Add(new DeviceItem { Manufacturer = device.Manufacturer, Model = device.Model, Revision = device.Revision, Bus = device.Bus, ReportId = device.Report != null && device.Report.Id != 0 ? device.Report.Id : 0 }); } ViewBag.repDevices = devices.OrderBy(device => device.Manufacturer).ThenBy(device => device.Model) .ThenBy(device => device.Revision).ThenBy(device => device.Bus) .ToList(); ViewData["devicesBusPieData"] = (from deviceBus in devices.Select(d => d.Bus).Distinct() let deviceBusCount = devices.Count(d => d.Bus == deviceBus) select new PieSeriesData { Name = deviceBus, Y = deviceBusCount / (double)devices.Count }).ToList(); ViewData["devicesManufacturerPieData"] = (from manufacturer in devices.Where(d => d.Manufacturer != null).Select(d => d.Manufacturer.ToLowerInvariant()) .Distinct() let manufacturerCount = devices.Count(d => d.Manufacturer?.ToLowerInvariant() == manufacturer) select new PieSeriesData { Name = manufacturer, Y = manufacturerCount / (double)devices.Count }) .ToList(); } } catch (Exception) { #if DEBUG throw; #endif return(Content("Could not read statistics")); } return(View()); }
/// <summary> /// Fills a SCSI device report with parameters and media tests specific to a Streaming device /// </summary> /// <param name="dev">Device</param> /// <param name="report">Device report</param> /// <param name="debug">If debug is enabled</param> internal static void Report(Device dev, ref DeviceReport report, bool debug) { if (report == null) { return; } bool sense; const uint TIMEOUT = 5; ConsoleKeyInfo pressedKey; report.SCSI.SequentialDevice = new sscType(); DicConsole.WriteLine("Querying SCSI READ BLOCK LIMITS..."); sense = dev.ReadBlockLimits(out byte[] buffer, out byte[] senseBuffer, TIMEOUT, out _); if (!sense) { BlockLimits.BlockLimitsData?decBl = BlockLimits.Decode(buffer); if (decBl.HasValue) { if (decBl.Value.granularity > 0) { report.SCSI.SequentialDevice.BlockSizeGranularitySpecified = true; report.SCSI.SequentialDevice.BlockSizeGranularity = decBl.Value.granularity; } if (decBl.Value.maxBlockLen > 0) { report.SCSI.SequentialDevice.MaxBlockLengthSpecified = true; report.SCSI.SequentialDevice.MaxBlockLength = decBl.Value.maxBlockLen; } if (decBl.Value.minBlockLen > 0) { report.SCSI.SequentialDevice.MinBlockLengthSpecified = true; report.SCSI.SequentialDevice.MinBlockLength = decBl.Value.minBlockLen; } } } DicConsole.WriteLine("Querying SCSI REPORT DENSITY SUPPORT..."); sense = dev.ReportDensitySupport(out buffer, out senseBuffer, false, false, TIMEOUT, out _); if (!sense) { DensitySupport.DensitySupportHeader?dsh = DensitySupport.DecodeDensity(buffer); if (dsh.HasValue) { report.SCSI.SequentialDevice.SupportedDensities = new SupportedDensity[dsh.Value.descriptors.Length]; for (int i = 0; i < dsh.Value.descriptors.Length; i++) { report.SCSI.SequentialDevice.SupportedDensities[i].BitsPerMm = dsh.Value.descriptors[i].bpmm; report.SCSI.SequentialDevice.SupportedDensities[i].Capacity = dsh.Value.descriptors[i].capacity; report.SCSI.SequentialDevice.SupportedDensities[i].DefaultDensity = dsh.Value.descriptors[i].defaultDensity; report.SCSI.SequentialDevice.SupportedDensities[i].Description = dsh.Value.descriptors[i].description; report.SCSI.SequentialDevice.SupportedDensities[i].Duplicate = dsh.Value.descriptors[i].duplicate; report.SCSI.SequentialDevice.SupportedDensities[i].Name = dsh.Value.descriptors[i].name; report.SCSI.SequentialDevice.SupportedDensities[i].Organization = dsh.Value.descriptors[i].organization; report.SCSI.SequentialDevice.SupportedDensities[i].PrimaryCode = dsh.Value.descriptors[i].primaryCode; report.SCSI.SequentialDevice.SupportedDensities[i].SecondaryCode = dsh.Value.descriptors[i].secondaryCode; report.SCSI.SequentialDevice.SupportedDensities[i].Tracks = dsh.Value.descriptors[i].tracks; report.SCSI.SequentialDevice.SupportedDensities[i].Width = dsh.Value.descriptors[i].width; report.SCSI.SequentialDevice.SupportedDensities[i].Writable = dsh.Value.descriptors[i].writable; } } } DicConsole.WriteLine("Querying SCSI REPORT DENSITY SUPPORT for medium types..."); sense = dev.ReportDensitySupport(out buffer, out senseBuffer, true, false, TIMEOUT, out _); if (!sense) { DensitySupport.MediaTypeSupportHeader?mtsh = DensitySupport.DecodeMediumType(buffer); if (mtsh.HasValue) { report.SCSI.SequentialDevice.SupportedMediaTypes = new SupportedMedia[mtsh.Value.descriptors.Length]; for (int i = 0; i < mtsh.Value.descriptors.Length; i++) { report.SCSI.SequentialDevice.SupportedMediaTypes[i].Description = mtsh.Value.descriptors[i].description; report.SCSI.SequentialDevice.SupportedMediaTypes[i].Length = mtsh.Value.descriptors[i].length; report.SCSI.SequentialDevice.SupportedMediaTypes[i].MediumType = mtsh.Value.descriptors[i].mediumType; report.SCSI.SequentialDevice.SupportedMediaTypes[i].Name = mtsh.Value.descriptors[i].name; report.SCSI.SequentialDevice.SupportedMediaTypes[i].Organization = mtsh.Value.descriptors[i].organization; report.SCSI.SequentialDevice.SupportedMediaTypes[i].Width = mtsh.Value.descriptors[i].width; if (mtsh.Value.descriptors[i].densityCodes == null) { continue; } report.SCSI.SequentialDevice.SupportedMediaTypes[i].DensityCodes = new int[mtsh.Value.descriptors[i].densityCodes.Length]; for (int j = 0; j < mtsh.Value.descriptors.Length; j++) { report.SCSI.SequentialDevice.SupportedMediaTypes[i].DensityCodes[j] = mtsh.Value.descriptors[i].densityCodes[j]; } } } } List <SequentialMedia> seqTests = new List <SequentialMedia>(); pressedKey = new ConsoleKeyInfo(); while (pressedKey.Key != ConsoleKey.N) { pressedKey = new ConsoleKeyInfo(); while (pressedKey.Key != ConsoleKey.Y && pressedKey.Key != ConsoleKey.N) { DicConsole.Write("Do you have media that you can insert in the drive? (Y/N): "); pressedKey = System.Console.ReadKey(); DicConsole.WriteLine(); } if (pressedKey.Key != ConsoleKey.Y) { continue; } DicConsole.WriteLine("Please insert it in the drive and press any key when it is ready."); System.Console.ReadKey(true); SequentialMedia seqTest = new SequentialMedia(); DicConsole.Write("Please write a description of the media type and press enter: "); seqTest.MediumTypeName = System.Console.ReadLine(); DicConsole.Write("Please write the media manufacturer and press enter: "); seqTest.Manufacturer = System.Console.ReadLine(); DicConsole.Write("Please write the media model and press enter: "); seqTest.Model = System.Console.ReadLine(); seqTest.MediaIsRecognized = true; dev.Load(out senseBuffer, TIMEOUT, out _); sense = dev.ScsiTestUnitReady(out senseBuffer, TIMEOUT, out _); if (sense) { FixedSense?decSense = Sense.DecodeFixed(senseBuffer); if (decSense.HasValue) { if (decSense.Value.ASC == 0x3A) { int leftRetries = 20; while (leftRetries > 0) { DicConsole.Write("\rWaiting for drive to become ready"); Thread.Sleep(2000); sense = dev.ScsiTestUnitReady(out senseBuffer, TIMEOUT, out _); if (!sense) { break; } leftRetries--; } seqTest.MediaIsRecognized &= !sense; } else if (decSense.Value.ASC == 0x04 && decSense.Value.ASCQ == 0x01) { int leftRetries = 20; while (leftRetries > 0) { DicConsole.Write("\rWaiting for drive to become ready"); Thread.Sleep(2000); sense = dev.ScsiTestUnitReady(out senseBuffer, TIMEOUT, out _); if (!sense) { break; } leftRetries--; } seqTest.MediaIsRecognized &= !sense; } else { seqTest.MediaIsRecognized = false; } } else { seqTest.MediaIsRecognized = false; } } if (seqTest.MediaIsRecognized) { Modes.DecodedMode?decMode = null; DicConsole.WriteLine("Querying SCSI MODE SENSE (10)..."); sense = dev.ModeSense10(out buffer, out senseBuffer, false, true, ScsiModeSensePageControl.Current, 0x3F, 0x00, TIMEOUT, out _); if (!sense && !dev.Error) { report.SCSI.SupportsModeSense10 = true; decMode = Modes.DecodeMode10(buffer, dev.ScsiType); if (debug) { seqTest.ModeSense10Data = buffer; } } DicConsole.WriteLine("Querying SCSI MODE SENSE..."); sense = dev.ModeSense(out buffer, out senseBuffer, TIMEOUT, out _); if (!sense && !dev.Error) { report.SCSI.SupportsModeSense6 = true; if (!decMode.HasValue) { decMode = Modes.DecodeMode6(buffer, dev.ScsiType); } if (debug) { seqTest.ModeSense6Data = buffer; } } if (decMode.HasValue) { seqTest.MediumType = (byte)decMode.Value.Header.MediumType; seqTest.MediumTypeSpecified = true; if (decMode.Value.Header.BlockDescriptors != null && decMode.Value.Header.BlockDescriptors.Length > 0) { seqTest.Density = (byte)decMode.Value.Header.BlockDescriptors[0].Density; seqTest.DensitySpecified = true; } } } DicConsole.WriteLine("Querying SCSI REPORT DENSITY SUPPORT for current media..."); sense = dev.ReportDensitySupport(out buffer, out senseBuffer, false, true, TIMEOUT, out _); if (!sense) { DensitySupport.DensitySupportHeader?dsh = DensitySupport.DecodeDensity(buffer); if (dsh.HasValue) { seqTest.SupportedDensities = new SupportedDensity[dsh.Value.descriptors.Length]; for (int i = 0; i < dsh.Value.descriptors.Length; i++) { seqTest.SupportedDensities[i].BitsPerMm = dsh.Value.descriptors[i].bpmm; seqTest.SupportedDensities[i].Capacity = dsh.Value.descriptors[i].capacity; seqTest.SupportedDensities[i].DefaultDensity = dsh.Value.descriptors[i].defaultDensity; seqTest.SupportedDensities[i].Description = dsh.Value.descriptors[i].description; seqTest.SupportedDensities[i].Duplicate = dsh.Value.descriptors[i].duplicate; seqTest.SupportedDensities[i].Name = dsh.Value.descriptors[i].name; seqTest.SupportedDensities[i].Organization = dsh.Value.descriptors[i].organization; seqTest.SupportedDensities[i].PrimaryCode = dsh.Value.descriptors[i].primaryCode; seqTest.SupportedDensities[i].SecondaryCode = dsh.Value.descriptors[i].secondaryCode; seqTest.SupportedDensities[i].Tracks = dsh.Value.descriptors[i].tracks; seqTest.SupportedDensities[i].Width = dsh.Value.descriptors[i].width; seqTest.SupportedDensities[i].Writable = dsh.Value.descriptors[i].writable; } } } DicConsole.WriteLine("Querying SCSI REPORT DENSITY SUPPORT for medium types for current media..."); sense = dev.ReportDensitySupport(out buffer, out senseBuffer, true, true, TIMEOUT, out _); if (!sense) { DensitySupport.MediaTypeSupportHeader?mtsh = DensitySupport.DecodeMediumType(buffer); if (mtsh.HasValue) { seqTest.SupportedMediaTypes = new SupportedMedia[mtsh.Value.descriptors.Length]; for (int i = 0; i < mtsh.Value.descriptors.Length; i++) { seqTest.SupportedMediaTypes[i].Description = mtsh.Value.descriptors[i].description; seqTest.SupportedMediaTypes[i].Length = mtsh.Value.descriptors[i].length; seqTest.SupportedMediaTypes[i].MediumType = mtsh.Value.descriptors[i].mediumType; seqTest.SupportedMediaTypes[i].Name = mtsh.Value.descriptors[i].name; seqTest.SupportedMediaTypes[i].Organization = mtsh.Value.descriptors[i].organization; seqTest.SupportedMediaTypes[i].Width = mtsh.Value.descriptors[i].width; if (mtsh.Value.descriptors[i].densityCodes == null) { continue; } seqTest.SupportedMediaTypes[i].DensityCodes = new int[mtsh.Value.descriptors[i].densityCodes.Length]; for (int j = 0; j < mtsh.Value.descriptors.Length; j++) { seqTest.SupportedMediaTypes[i].DensityCodes[j] = mtsh.Value.descriptors[i].densityCodes[j]; } } } } seqTest.CanReadMediaSerialSpecified = true; DicConsole.WriteLine("Trying SCSI READ MEDIA SERIAL NUMBER..."); seqTest.CanReadMediaSerial = !dev.ReadMediaSerialNumber(out buffer, out senseBuffer, TIMEOUT, out _); seqTests.Add(seqTest); } report.SCSI.SequentialDevice.TestedMedia = seqTests.ToArray(); }
public Device(string manufacturer, string model, string revision, DeviceType type, DeviceReport report) { WhenAdded = DateTime.UtcNow; Manufacturer = manufacturer; Model = model; Revision = revision; Type = type; USB = USB.MapUsb(report.USB); FireWire = FireWire.MapFirewire(report.FireWire); PCMCIA = PCMCIA.MapPcmcia(report.PCMCIA); ATA = ATA.MapAta(report.ATA); ATAPI = ATA.MapAta(report.ATAPI); SCSI = Models.SCSI.SCSI.MapScsi(report.SCSI); MultiMediaCard = SecureDigital.MapSd(report.MultiMediaCard); SecureDigital = SecureDigital.MapSd(report.SecureDigital); WhenAdded = DateTime.UtcNow; IsValid = true; }
public async Task <IActionResult> UploadReport() { var response = new ContentResult { StatusCode = (int)HttpStatusCode.OK, ContentType = "text/plain" }; try { var newReport = new DeviceReport(); HttpRequest request = HttpContext.Request; var xs = new XmlSerializer(newReport.GetType()); newReport = (DeviceReport)xs.Deserialize(new StringReader(await new StreamReader(request.Body).ReadToEndAsync())); if (newReport == null) { response.Content = "notstats"; return(response); } var reportV2 = new DeviceReportV2(newReport); var jsonSw = new StringWriter(); await jsonSw.WriteAsync(JsonConvert.SerializeObject(reportV2, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })); string reportV2String = jsonSw.ToString(); jsonSw.Close(); var newUploadedReport = new UploadedReport(reportV2); // Ensure CHS and CurrentCHS are not duplicates if (newUploadedReport.ATA?.ReadCapabilities?.CHS != null && newUploadedReport.ATA?.ReadCapabilities?.CurrentCHS != null) { if (newUploadedReport.ATA.ReadCapabilities.CHS.Cylinders == newUploadedReport.ATA.ReadCapabilities.CurrentCHS.Cylinders && newUploadedReport.ATA.ReadCapabilities.CHS.Heads == newUploadedReport.ATA.ReadCapabilities.CurrentCHS.Heads && newUploadedReport.ATA.ReadCapabilities.CHS.Sectors == newUploadedReport.ATA.ReadCapabilities.CurrentCHS.Sectors) { newUploadedReport.ATA.ReadCapabilities.CHS = newUploadedReport.ATA.ReadCapabilities.CurrentCHS; } } // Check if the CHS or CurrentCHS of this report already exist in the database if (newUploadedReport.ATA?.ReadCapabilities?.CHS != null) { Chs existingChs = _ctx.Chs.FirstOrDefault(c => c.Cylinders == newUploadedReport.ATA.ReadCapabilities.CHS.Cylinders && c.Heads == newUploadedReport.ATA.ReadCapabilities.CHS.Heads && c.Sectors == newUploadedReport.ATA.ReadCapabilities.CHS.Sectors); if (existingChs != null) { newUploadedReport.ATA.ReadCapabilities.CHS = existingChs; } } if (newUploadedReport.ATA?.ReadCapabilities?.CurrentCHS != null) { Chs existingChs = _ctx.Chs.FirstOrDefault(c => c.Cylinders == newUploadedReport.ATA.ReadCapabilities.CurrentCHS. Cylinders && c.Heads == newUploadedReport.ATA.ReadCapabilities.CurrentCHS.Heads && c.Sectors == newUploadedReport.ATA.ReadCapabilities.CurrentCHS.Sectors); if (existingChs != null) { newUploadedReport.ATA.ReadCapabilities.CurrentCHS = existingChs; } } if (newUploadedReport.ATA?.RemovableMedias != null) { foreach (TestedMedia media in newUploadedReport.ATA.RemovableMedias) { if (media.CHS != null && media.CurrentCHS != null) { if (media.CHS.Cylinders == media.CurrentCHS.Cylinders && media.CHS.Heads == media.CurrentCHS.Heads && media.CHS.Sectors == media.CurrentCHS.Sectors) { media.CHS = media.CurrentCHS; } } if (media.CHS != null) { Chs existingChs = _ctx.Chs.FirstOrDefault(c => c.Cylinders == media.CHS.Cylinders && c.Heads == media.CHS.Heads && c.Sectors == media.CHS.Sectors); if (existingChs != null) { media.CHS = existingChs; } } if (media.CHS != null) { Chs existingChs = _ctx.Chs.FirstOrDefault(c => c.Cylinders == media.CurrentCHS.Cylinders && c.Heads == media.CurrentCHS.Heads && c.Sectors == media.CurrentCHS.Sectors); if (existingChs != null) { media.CurrentCHS = existingChs; } } } } await _ctx.Reports.AddAsync(newUploadedReport); await _ctx.SaveChangesAsync(); var pgpIn = new MemoryStream(Encoding.UTF8.GetBytes(reportV2String)); var pgpOut = new MemoryStream(); var pgp = new ChoPGPEncryptDecrypt(); await pgp.EncryptAsync(pgpIn, pgpOut, Path.Combine(_environment.ContentRootPath ?? throw new InvalidOperationException(), "public.asc")); pgpOut.Position = 0; reportV2String = Encoding.UTF8.GetString(pgpOut.ToArray()); var message = new MimeMessage { Subject = "New device report (old version)", Body = new TextPart("plain") { Text = reportV2String } }; message.From.Add(new MailboxAddress("Aaru Server", "*****@*****.**")); message.To.Add(new MailboxAddress("Natalia Portillo", "*****@*****.**")); using (var client = new SmtpClient()) { await client.ConnectAsync("mail.claunia.com", 25, false); await client.SendAsync(message); await client.DisconnectAsync(true); } response.Content = "ok"; return(response); } // ReSharper disable once RedundantCatchClause catch { #if DEBUG if (Debugger.IsAttached) { throw; } #endif response.Content = "error"; return(response); } }
/// <summary>Dumps an ATA device</summary> void Ata() { if (_dumpRaw) { if (_force) { ErrorMessage?.Invoke("Raw dumping not yet supported in ATA devices, continuing..."); } else { StoppingErrorMessage?.Invoke("Raw dumping not yet supported in ATA devices, aborting..."); return; } } const ushort ataProfile = 0x0001; const uint timeout = 5; double imageWriteDuration = 0; MediaType mediaType = MediaType.Unknown; UpdateStatus?.Invoke("Requesting ATA IDENTIFY DEVICE."); _dumpLog.WriteLine("Requesting ATA IDENTIFY DEVICE."); bool sense = _dev.AtaIdentify(out byte[] cmdBuf, out AtaErrorRegistersChs errorChs); if (sense) { _errorLog?.WriteLine("ATA IDENTIFY DEVICE", _dev.Error, _dev.LastError, errorChs); } else if (Identify.Decode(cmdBuf).HasValue) { Identify.IdentifyDevice?ataIdNullable = Identify.Decode(cmdBuf); if (ataIdNullable != null) { Identify.IdentifyDevice ataId = ataIdNullable.Value; byte[] ataIdentify = cmdBuf; cmdBuf = new byte[0]; DateTime start; DateTime end; double totalDuration = 0; double currentSpeed = 0; double maxSpeed = double.MinValue; double minSpeed = double.MaxValue; // Initialize reader UpdateStatus?.Invoke("Initializing reader."); _dumpLog.WriteLine("Initializing reader."); var ataReader = new Reader(_dev, timeout, ataIdentify, _errorLog); // Fill reader blocks ulong blocks = ataReader.GetDeviceBlocks(); // Check block sizes if (ataReader.GetBlockSize()) { _dumpLog.WriteLine("ERROR: Cannot get block size: {0}.", ataReader.ErrorMessage); ErrorMessage(ataReader.ErrorMessage); return; } uint blockSize = ataReader.LogicalBlockSize; uint physicalSectorSize = ataReader.PhysicalBlockSize; if (ataReader.FindReadCommand()) { _dumpLog.WriteLine("ERROR: Cannot find correct read command: {0}.", ataReader.ErrorMessage); ErrorMessage(ataReader.ErrorMessage); return; } // Check how many blocks to read, if error show and return if (ataReader.GetBlocksToRead(_maximumReadable)) { _dumpLog.WriteLine("ERROR: Cannot get blocks to read: {0}.", ataReader.ErrorMessage); ErrorMessage(ataReader.ErrorMessage); return; } uint blocksToRead = ataReader.BlocksToRead; ushort cylinders = ataReader.Cylinders; byte heads = ataReader.Heads; byte sectors = ataReader.Sectors; UpdateStatus?.Invoke($"Device reports {blocks} blocks ({blocks * blockSize} bytes)."); UpdateStatus?. Invoke($"Device reports {cylinders} cylinders {heads} heads {sectors} sectors per track."); UpdateStatus?.Invoke($"Device can read {blocksToRead} blocks at a time."); UpdateStatus?.Invoke($"Device reports {blockSize} bytes per logical block."); UpdateStatus?.Invoke($"Device reports {physicalSectorSize} bytes per physical block."); _dumpLog.WriteLine("Device reports {0} blocks ({1} bytes).", blocks, blocks * blockSize); _dumpLog.WriteLine("Device reports {0} cylinders {1} heads {2} sectors per track.", cylinders, heads, sectors); _dumpLog.WriteLine("Device can read {0} blocks at a time.", blocksToRead); _dumpLog.WriteLine("Device reports {0} bytes per logical block.", blockSize); _dumpLog.WriteLine("Device reports {0} bytes per physical block.", physicalSectorSize); bool removable = !_dev.IsCompactFlash && ataId.GeneralConfiguration.HasFlag(Identify.GeneralConfigurationBit.Removable); DumpHardwareType currentTry = null; ExtentsULong extents = null; ResumeSupport.Process(ataReader.IsLba, removable, blocks, _dev.Manufacturer, _dev.Model, _dev.Serial, _dev.PlatformId, ref _resume, ref currentTry, ref extents, _dev.FirmwareRevision, _private); if (currentTry == null || extents == null) { StoppingErrorMessage?.Invoke("Could not process resume file, not continuing..."); return; } MhddLog mhddLog; IbgLog ibgLog; double duration; bool ret = true; if (_dev.IsUsb && _dev.UsbDescriptors != null && !_outputPlugin.SupportedMediaTags.Contains(MediaTagType.USB_Descriptors)) { ret = false; _dumpLog.WriteLine("Output format does not support USB descriptors."); ErrorMessage("Output format does not support USB descriptors."); } if (_dev.IsPcmcia && _dev.Cis != null && !_outputPlugin.SupportedMediaTags.Contains(MediaTagType.PCMCIA_CIS)) { ret = false; _dumpLog.WriteLine("Output format does not support PCMCIA CIS descriptors."); ErrorMessage("Output format does not support PCMCIA CIS descriptors."); } if (!_outputPlugin.SupportedMediaTags.Contains(MediaTagType.ATA_IDENTIFY)) { ret = false; _dumpLog.WriteLine("Output format does not support ATA IDENTIFY."); ErrorMessage("Output format does not support ATA IDENTIFY."); } if (!ret) { _dumpLog.WriteLine("Several media tags not supported, {0}continuing...", _force ? "" : "not "); if (_force) { ErrorMessage("Several media tags not supported, continuing..."); } else { StoppingErrorMessage?.Invoke("Several media tags not supported, not continuing..."); return; } } mediaType = MediaTypeFromDevice.GetFromAta(_dev.Manufacturer, _dev.Model, _dev.IsRemovable, _dev.IsCompactFlash, _dev.IsPcmcia, blocks); ret = _outputPlugin.Create(_outputPath, mediaType, _formatOptions, blocks, blockSize); // Cannot create image if (!ret) { _dumpLog.WriteLine("Error creating output image, not continuing."); _dumpLog.WriteLine(_outputPlugin.ErrorMessage); StoppingErrorMessage?.Invoke("Error creating output image, not continuing." + Environment.NewLine + _outputPlugin.ErrorMessage); return; } // Setting geometry _outputPlugin.SetGeometry(cylinders, heads, sectors); if (ataReader.IsLba) { UpdateStatus?.Invoke($"Reading {blocksToRead} sectors at a time."); if (_skip < blocksToRead) { _skip = blocksToRead; } mhddLog = new MhddLog(_outputPrefix + ".mhddlog.bin", _dev, blocks, blockSize, blocksToRead, _private); ibgLog = new IbgLog(_outputPrefix + ".ibg", ataProfile); if (_resume.NextBlock > 0) { UpdateStatus?.Invoke($"Resuming from block {_resume.NextBlock}."); _dumpLog.WriteLine("Resuming from block {0}.", _resume.NextBlock); } bool newTrim = false; start = DateTime.UtcNow; DateTime timeSpeedStart = DateTime.UtcNow; ulong sectorSpeedStart = 0; InitProgress?.Invoke(); for (ulong i = _resume.NextBlock; i < blocks; i += blocksToRead) { if (_aborted) { currentTry.Extents = ExtentsConverter.ToMetadata(extents); UpdateStatus?.Invoke("Aborted!"); _dumpLog.WriteLine("Aborted!"); break; } if (blocks - i < blocksToRead) { blocksToRead = (byte)(blocks - i); } if (currentSpeed > maxSpeed && currentSpeed > 0) { maxSpeed = currentSpeed; } if (currentSpeed < minSpeed && currentSpeed > 0) { minSpeed = currentSpeed; } UpdateProgress?.Invoke($"Reading sector {i} of {blocks} ({currentSpeed:F3} MiB/sec.)", (long)i, (long)blocks); bool error = ataReader.ReadBlocks(out cmdBuf, i, blocksToRead, out duration); if (!error) { mhddLog.Write(i, duration); ibgLog.Write(i, currentSpeed * 1024); DateTime writeStart = DateTime.Now; _outputPlugin.WriteSectors(cmdBuf, i, blocksToRead); imageWriteDuration += (DateTime.Now - writeStart).TotalSeconds; extents.Add(i, blocksToRead, true); } else { if (i + _skip > blocks) { _skip = (uint)(blocks - i); } for (ulong b = i; b < i + _skip; b++) { _resume.BadBlocks.Add(b); } mhddLog.Write(i, duration < 500 ? 65535 : duration); ibgLog.Write(i, 0); DateTime writeStart = DateTime.Now; _outputPlugin.WriteSectors(new byte[blockSize * _skip], i, _skip); imageWriteDuration += (DateTime.Now - writeStart).TotalSeconds; _dumpLog.WriteLine("Skipping {0} blocks from errored block {1}.", _skip, i); i += _skip - blocksToRead; newTrim = true; } sectorSpeedStart += blocksToRead; _resume.NextBlock = i + blocksToRead; double elapsed = (DateTime.UtcNow - timeSpeedStart).TotalSeconds; if (elapsed < 1) { continue; } currentSpeed = (sectorSpeedStart * blockSize) / (1048576 * elapsed); sectorSpeedStart = 0; timeSpeedStart = DateTime.UtcNow; } end = DateTime.Now; EndProgress?.Invoke(); mhddLog.Close(); ibgLog.Close(_dev, blocks, blockSize, (end - start).TotalSeconds, currentSpeed * 1024, (blockSize * (double)(blocks + 1)) / 1024 / (totalDuration / 1000), _devicePath); UpdateStatus?.Invoke($"Dump finished in {(end - start).TotalSeconds} seconds."); UpdateStatus?. Invoke($"Average dump speed {((double)blockSize * (double)(blocks + 1)) / 1024 / (totalDuration / 1000):F3} KiB/sec."); UpdateStatus?. Invoke($"Average write speed {((double)blockSize * (double)(blocks + 1)) / 1024 / imageWriteDuration:F3} KiB/sec."); _dumpLog.WriteLine("Dump finished in {0} seconds.", (end - start).TotalSeconds); _dumpLog.WriteLine("Average dump speed {0:F3} KiB/sec.", ((double)blockSize * (double)(blocks + 1)) / 1024 / (totalDuration / 1000)); _dumpLog.WriteLine("Average write speed {0:F3} KiB/sec.", ((double)blockSize * (double)(blocks + 1)) / 1024 / imageWriteDuration); #region Trimming if (_resume.BadBlocks.Count > 0 && !_aborted && _trim && newTrim) { start = DateTime.UtcNow; UpdateStatus?.Invoke("Trimming skipped sectors"); _dumpLog.WriteLine("Trimming skipped sectors"); ulong[] tmpArray = _resume.BadBlocks.ToArray(); InitProgress?.Invoke(); foreach (ulong badSector in tmpArray) { if (_aborted) { currentTry.Extents = ExtentsConverter.ToMetadata(extents); UpdateStatus?.Invoke("Aborted!"); _dumpLog.WriteLine("Aborted!"); break; } PulseProgress?.Invoke($"Trimming sector {badSector}"); bool error = ataReader.ReadBlock(out cmdBuf, badSector, out duration); totalDuration += duration; if (error) { continue; } _resume.BadBlocks.Remove(badSector); extents.Add(badSector); _outputPlugin.WriteSector(cmdBuf, badSector); } EndProgress?.Invoke(); end = DateTime.UtcNow; UpdateStatus?.Invoke($"Trimming finished in {(end - start).TotalSeconds} seconds."); _dumpLog.WriteLine("Trimming finished in {0} seconds.", (end - start).TotalSeconds); } #endregion Trimming #region Error handling if (_resume.BadBlocks.Count > 0 && !_aborted && _retryPasses > 0) { int pass = 1; bool forward = true; InitProgress?.Invoke(); repeatRetryLba: ulong[] tmpArray = _resume.BadBlocks.ToArray(); foreach (ulong badSector in tmpArray) { if (_aborted) { currentTry.Extents = ExtentsConverter.ToMetadata(extents); UpdateStatus?.Invoke("Aborted!"); _dumpLog.WriteLine("Aborted!"); break; } PulseProgress?.Invoke(string.Format("Retrying sector {0}, pass {1}, {3}{2}", badSector, pass, forward ? "forward" : "reverse", _persistent ? "recovering partial data, " : "")); bool error = ataReader.ReadBlock(out cmdBuf, badSector, out duration); totalDuration += duration; if (!error) { _resume.BadBlocks.Remove(badSector); extents.Add(badSector); _outputPlugin.WriteSector(cmdBuf, badSector); UpdateStatus?.Invoke($"Correctly retried block {badSector} in pass {pass}."); _dumpLog.WriteLine("Correctly retried block {0} in pass {1}.", badSector, pass); } else if (_persistent) { _outputPlugin.WriteSector(cmdBuf, badSector); } } if (pass < _retryPasses && !_aborted && _resume.BadBlocks.Count > 0) { pass++; forward = !forward; _resume.BadBlocks.Sort(); if (!forward) { _resume.BadBlocks.Reverse(); } goto repeatRetryLba; } EndProgress?.Invoke(); } #endregion Error handling LBA currentTry.Extents = ExtentsConverter.ToMetadata(extents); } else { mhddLog = new MhddLog(_outputPrefix + ".mhddlog.bin", _dev, blocks, blockSize, blocksToRead, _private); ibgLog = new IbgLog(_outputPrefix + ".ibg", ataProfile); ulong currentBlock = 0; blocks = (ulong)(cylinders * heads * sectors); start = DateTime.UtcNow; DateTime timeSpeedStart = DateTime.UtcNow; ulong sectorSpeedStart = 0; InitProgress?.Invoke(); for (ushort cy = 0; cy < cylinders; cy++) { for (byte hd = 0; hd < heads; hd++) { for (byte sc = 1; sc < sectors; sc++) { if (_aborted) { currentTry.Extents = ExtentsConverter.ToMetadata(extents); UpdateStatus?.Invoke("Aborted!"); _dumpLog.WriteLine("Aborted!"); break; } if (currentSpeed > maxSpeed && currentSpeed > 0) { maxSpeed = currentSpeed; } if (currentSpeed < minSpeed && currentSpeed > 0) { minSpeed = currentSpeed; } PulseProgress?. Invoke($"Reading cylinder {cy} head {hd} sector {sc} ({currentSpeed:F3} MiB/sec.)"); bool error = ataReader.ReadChs(out cmdBuf, cy, hd, sc, out duration); totalDuration += duration; if (!error) { mhddLog.Write(currentBlock, duration); ibgLog.Write(currentBlock, currentSpeed * 1024); DateTime writeStart = DateTime.Now; _outputPlugin.WriteSector(cmdBuf, (ulong)((((cy * heads) + hd) * sectors) + (sc - 1))); imageWriteDuration += (DateTime.Now - writeStart).TotalSeconds; extents.Add(currentBlock); _dumpLog.WriteLine("Error reading cylinder {0} head {1} sector {2}.", cy, hd, sc); } else { _resume.BadBlocks.Add(currentBlock); mhddLog.Write(currentBlock, duration < 500 ? 65535 : duration); ibgLog.Write(currentBlock, 0); DateTime writeStart = DateTime.Now; _outputPlugin.WriteSector(new byte[blockSize], (ulong)((((cy * heads) + hd) * sectors) + (sc - 1))); imageWriteDuration += (DateTime.Now - writeStart).TotalSeconds; } sectorSpeedStart++; currentBlock++; double elapsed = (DateTime.UtcNow - timeSpeedStart).TotalSeconds; if (elapsed < 1) { continue; } currentSpeed = (sectorSpeedStart * blockSize) / (1048576 * elapsed); sectorSpeedStart = 0; timeSpeedStart = DateTime.UtcNow; } } } end = DateTime.Now; EndProgress?.Invoke(); mhddLog.Close(); ibgLog.Close(_dev, blocks, blockSize, (end - start).TotalSeconds, currentSpeed * 1024, (blockSize * (double)(blocks + 1)) / 1024 / (totalDuration / 1000), _devicePath); UpdateStatus?.Invoke($"Dump finished in {(end - start).TotalSeconds} seconds."); UpdateStatus?. Invoke($"Average dump speed {((double)blockSize * (double)(blocks + 1)) / 1024 / (totalDuration / 1000):F3} KiB/sec."); UpdateStatus?. Invoke($"Average write speed {((double)blockSize * (double)(blocks + 1)) / 1024 / (imageWriteDuration / 1000):F3} KiB/sec."); _dumpLog.WriteLine("Dump finished in {0} seconds.", (end - start).TotalSeconds); _dumpLog.WriteLine("Average dump speed {0:F3} KiB/sec.", ((double)blockSize * (double)(blocks + 1)) / 1024 / (totalDuration / 1000)); _dumpLog.WriteLine("Average write speed {0:F3} KiB/sec.", ((double)blockSize * (double)(blocks + 1)) / 1024 / (imageWriteDuration / 1000)); } foreach (ulong bad in _resume.BadBlocks) { _dumpLog.WriteLine("Sector {0} could not be read.", bad); } _outputPlugin.SetDumpHardware(_resume.Tries); // TODO: Non-removable var metadata = new CommonTypes.Structs.ImageInfo { Application = "Aaru", ApplicationVersion = Version.GetVersion() }; if (!_outputPlugin.SetMetadata(metadata)) { ErrorMessage?.Invoke("Error {0} setting metadata, continuing..." + Environment.NewLine + _outputPlugin.ErrorMessage); } if (_preSidecar != null) { _outputPlugin.SetCicmMetadata(_preSidecar); } _dumpLog.WriteLine("Closing output file."); UpdateStatus?.Invoke("Closing output file."); DateTime closeStart = DateTime.Now; _outputPlugin.Close(); DateTime closeEnd = DateTime.Now; UpdateStatus?.Invoke($"Closed in {(closeEnd - closeStart).TotalSeconds} seconds."); _dumpLog.WriteLine("Closed in {0} seconds.", (closeEnd - closeStart).TotalSeconds); if (_aborted) { _dumpLog.WriteLine("Aborted!"); UpdateStatus?.Invoke("Aborted!"); return; } double totalChkDuration = 0; if (_metadata) { _dumpLog.WriteLine("Creating sidecar."); UpdateStatus?.Invoke("Creating sidecar."); var filters = new FiltersList(); IFilter filter = filters.GetFilter(_outputPath); IMediaImage inputPlugin = ImageFormat.Detect(filter); if (!inputPlugin.Open(filter)) { StoppingErrorMessage?.Invoke("Could not open created image."); return; } DateTime chkStart = DateTime.UtcNow; _sidecarClass = new Sidecar(inputPlugin, _outputPath, filter.Id, _encoding); _sidecarClass.InitProgressEvent += InitProgress; _sidecarClass.UpdateProgressEvent += UpdateProgress; _sidecarClass.EndProgressEvent += EndProgress; _sidecarClass.InitProgressEvent2 += InitProgress2; _sidecarClass.UpdateProgressEvent2 += UpdateProgress2; _sidecarClass.EndProgressEvent2 += EndProgress2; _sidecarClass.UpdateStatusEvent += UpdateStatus; CICMMetadataType sidecar = _sidecarClass.Create(); if (_preSidecar != null) { _preSidecar.BlockMedia = sidecar.BlockMedia; sidecar = _preSidecar; } if (_dev.IsUsb && _dev.UsbDescriptors != null) { _dumpLog.WriteLine("Reading USB descriptors."); UpdateStatus?.Invoke("Reading USB descriptors."); ret = _outputPlugin.WriteMediaTag(_dev.UsbDescriptors, MediaTagType.USB_Descriptors); if (ret) { sidecar.BlockMedia[0].USB = new USBType { ProductID = _dev.UsbProductId, VendorID = _dev.UsbVendorId, Descriptors = new DumpType { Image = _outputPath, Size = (ulong)_dev.UsbDescriptors.Length, Checksums = Checksum.GetChecksums(_dev.UsbDescriptors).ToArray() } } } ; } if (_dev.IsPcmcia && _dev.Cis != null) { _dumpLog.WriteLine("Reading PCMCIA CIS."); UpdateStatus?.Invoke("Reading PCMCIA CIS."); ret = _outputPlugin.WriteMediaTag(_dev.Cis, MediaTagType.PCMCIA_CIS); if (ret) { sidecar.BlockMedia[0].PCMCIA = new PCMCIAType { CIS = new DumpType { Image = _outputPath, Size = (ulong)_dev.Cis.Length, Checksums = Checksum.GetChecksums(_dev.Cis).ToArray() } } } ; _dumpLog.WriteLine("Decoding PCMCIA CIS."); UpdateStatus?.Invoke("Decoding PCMCIA CIS."); Tuple[] tuples = CIS.GetTuples(_dev.Cis); if (tuples != null) { foreach (Tuple tuple in tuples) { switch (tuple.Code) { case TupleCodes.CISTPL_MANFID: ManufacturerIdentificationTuple manufacturerId = CIS.DecodeManufacturerIdentificationTuple(tuple); if (manufacturerId != null) { sidecar.BlockMedia[0].PCMCIA.ManufacturerCode = manufacturerId.ManufacturerID; sidecar.BlockMedia[0].PCMCIA.CardCode = manufacturerId.CardID; sidecar.BlockMedia[0].PCMCIA.ManufacturerCodeSpecified = true; sidecar.BlockMedia[0].PCMCIA.CardCodeSpecified = true; } break; case TupleCodes.CISTPL_VERS_1: Level1VersionTuple version = CIS.DecodeLevel1VersionTuple(tuple); if (version != null) { sidecar.BlockMedia[0].PCMCIA.Manufacturer = version.Manufacturer; sidecar.BlockMedia[0].PCMCIA.ProductName = version.Product; sidecar.BlockMedia[0].PCMCIA.Compliance = $"{version.MajorVersion}.{version.MinorVersion}"; sidecar.BlockMedia[0].PCMCIA.AdditionalInformation = version.AdditionalInformation; } break; } } } } if (!_private) { DeviceReport.ClearIdentify(ataIdentify); } ret = _outputPlugin.WriteMediaTag(ataIdentify, MediaTagType.ATA_IDENTIFY); if (ret) { sidecar.BlockMedia[0].ATA = new ATAType { Identify = new DumpType { Image = _outputPath, Size = (ulong)cmdBuf.Length, Checksums = Checksum.GetChecksums(cmdBuf).ToArray() } } } ; DateTime chkEnd = DateTime.UtcNow; totalChkDuration = (chkEnd - chkStart).TotalMilliseconds; UpdateStatus?.Invoke($"Sidecar created in {(chkEnd - chkStart).TotalSeconds} seconds."); UpdateStatus?. Invoke($"Average checksum speed {((double)blockSize * (double)(blocks + 1)) / 1024 / (totalChkDuration / 1000):F3} KiB/sec."); _dumpLog.WriteLine("Sidecar created in {0} seconds.", (chkEnd - chkStart).TotalSeconds); _dumpLog.WriteLine("Average checksum speed {0:F3} KiB/sec.", ((double)blockSize * (double)(blocks + 1)) / 1024 / (totalChkDuration / 1000)); List <(ulong start, string type)> filesystems = new List <(ulong start, string type)>(); if (sidecar.BlockMedia[0].FileSystemInformation != null) { filesystems.AddRange(from partition in sidecar.BlockMedia[0].FileSystemInformation where partition.FileSystems != null from fileSystem in partition.FileSystems select(partition.StartSector, fileSystem.Type)); } if (filesystems.Count > 0) { foreach (var filesystem in filesystems.Select(o => new { o.start, o.type }).Distinct()) { UpdateStatus?. Invoke($"Found filesystem {filesystem.type} at sector {filesystem.start}"); _dumpLog.WriteLine("Found filesystem {0} at sector {1}", filesystem.type, filesystem.start); } } (string type, string subType) = CommonTypes.Metadata.MediaType.MediaTypeToString(mediaType); sidecar.BlockMedia[0].DiskType = type; sidecar.BlockMedia[0].DiskSubType = subType; sidecar.BlockMedia[0].Interface = "ATA"; sidecar.BlockMedia[0].LogicalBlocks = blocks; sidecar.BlockMedia[0].PhysicalBlockSize = physicalSectorSize; sidecar.BlockMedia[0].LogicalBlockSize = blockSize; sidecar.BlockMedia[0].Manufacturer = _dev.Manufacturer; sidecar.BlockMedia[0].Model = _dev.Model; if (!_private) { sidecar.BlockMedia[0].Serial = _dev.Serial; } sidecar.BlockMedia[0].Size = blocks * blockSize; if (cylinders > 0 && heads > 0 && sectors > 0) { sidecar.BlockMedia[0].Cylinders = cylinders; sidecar.BlockMedia[0].CylindersSpecified = true; sidecar.BlockMedia[0].Heads = heads; sidecar.BlockMedia[0].HeadsSpecified = true; sidecar.BlockMedia[0].SectorsPerTrack = sectors; sidecar.BlockMedia[0].SectorsPerTrackSpecified = true; } UpdateStatus?.Invoke("Writing metadata sidecar"); var xmlFs = new FileStream(_outputPrefix + ".cicm.xml", FileMode.Create); var xmlSer = new XmlSerializer(typeof(CICMMetadataType)); xmlSer.Serialize(xmlFs, sidecar); xmlFs.Close(); } UpdateStatus?.Invoke(""); UpdateStatus?. Invoke($"Took a total of {(end - start).TotalSeconds:F3} seconds ({totalDuration / 1000:F3} processing commands, {totalChkDuration / 1000:F3} checksumming, {imageWriteDuration:F3} writing, {(closeEnd - closeStart).TotalSeconds:F3} closing)."); UpdateStatus?. Invoke($"Average speed: {((double)blockSize * (double)(blocks + 1)) / 1048576 / (totalDuration / 1000):F3} MiB/sec."); if (maxSpeed > 0) { UpdateStatus?.Invoke($"Fastest speed burst: {maxSpeed:F3} MiB/sec."); } if (minSpeed > 0 && minSpeed < double.MaxValue) { UpdateStatus?.Invoke($"Slowest speed burst: {minSpeed:F3} MiB/sec."); } UpdateStatus?.Invoke($"{_resume.BadBlocks.Count} sectors could not be read."); if (_resume.BadBlocks.Count > 0) { _resume.BadBlocks.Sort(); } UpdateStatus?.Invoke(""); } Statistics.AddMedia(mediaType, true); } else { StoppingErrorMessage?.Invoke("Unable to communicate with ATA device."); } } } }
public Device(DeviceReport report) { WhenAdded = DateTime.UtcNow; if (report.SecureDigital != null) { Type = DeviceType.SecureDigital; } else if (report.MultiMediaCard != null) { Type = DeviceType.MMC; } else if (report.FireWire != null) { Type = DeviceType.FireWire; } else if (report.USB != null) { Type = DeviceType.USB; } else if (report.PCMCIA != null) { Type = DeviceType.PCMCIA; } else if (report.ATAPI != null) { Type = DeviceType.ATAPI; } else if (report.ATA != null) { Type = DeviceType.ATA; } else if (report.SCSI?.Inquiry != null) { Type = DeviceType.SCSI; } if (report.CompactFlashSpecified && report.CompactFlash) { Type = DeviceType.CompactFlash; } if (!string.IsNullOrWhiteSpace(report.FireWire?.Manufacturer)) { Manufacturer = report.FireWire.Manufacturer; } else if (!string.IsNullOrWhiteSpace(report.USB?.Manufacturer)) { Manufacturer = report.USB.Manufacturer; } else if (!string.IsNullOrWhiteSpace(report.SCSI?.Inquiry?.VendorIdentification)) { Manufacturer = report.SCSI.Inquiry.VendorIdentification; } else if (!string.IsNullOrWhiteSpace(report.PCMCIA?.Manufacturer)) { Manufacturer = report.PCMCIA.Manufacturer; } else if (!string.IsNullOrWhiteSpace(report.ATAPI?.Model)) { string[] atapiSplit = report.ATAPI.Model.Split(' '); Manufacturer = atapiSplit.Length > 1 ? atapiSplit[0] : report.ATAPI.Model; } else if (!string.IsNullOrWhiteSpace(report.ATA?.Model)) { string[] ataSplit = report.ATA.Model.Split(' '); Manufacturer = ataSplit.Length > 1 ? ataSplit[0] : report.ATA.Model; } if (!string.IsNullOrWhiteSpace(report.FireWire?.Product)) { Model = report.FireWire.Product; } else if (!string.IsNullOrWhiteSpace(report.USB?.Product)) { Model = report.USB.Product; } else if (!string.IsNullOrWhiteSpace(report.SCSI?.Inquiry?.ProductIdentification)) { Model = report.SCSI.Inquiry.ProductIdentification; } else if (!string.IsNullOrWhiteSpace(report.PCMCIA?.ProductName)) { Model = report.PCMCIA.ProductName; } else if (!string.IsNullOrWhiteSpace(report.ATAPI?.Model)) { string[] atapiSplit = report.ATAPI.Model.Split(' '); Model = atapiSplit.Length > 1 ? report.ATAPI.Model.Substring(atapiSplit[0].Length + 1) : null; } else if (!string.IsNullOrWhiteSpace(report.ATA?.Model)) { string[] ataSplit = report.ATA.Model.Split(' '); Model = ataSplit.Length > 1 ? report.ATA.Model.Substring(ataSplit[0].Length + 1) : null; } if (!string.IsNullOrWhiteSpace(report.SCSI?.Inquiry?.ProductRevisionLevel)) { Revision = report.SCSI.Inquiry.ProductRevisionLevel; } else if (!string.IsNullOrWhiteSpace(report.ATAPI?.FirmwareRevision)) { Revision = report.ATAPI.FirmwareRevision; } else if (!string.IsNullOrWhiteSpace(report.ATA?.FirmwareRevision)) { Revision = report.ATA.FirmwareRevision; } USB = USB.MapUsb(report.USB); FireWire = FireWire.MapFirewire(report.FireWire); PCMCIA = PCMCIA.MapPcmcia(report.PCMCIA); ATA = ATA.MapAta(report.ATA); ATAPI = ATA.MapAta(report.ATAPI); SCSI = Models.SCSI.SCSI.MapScsi(report.SCSI); MultiMediaCard = SecureDigital.MapSd(report.MultiMediaCard); SecureDigital = SecureDigital.MapSd(report.SecureDigital); WhenAdded = DateTime.UtcNow; IsValid = true; }
public TlvBody(ushort subCmd, uint uin, string password, uint ssoseq, byte[] tgtgKey) : base() { // 設備訊息上報 var deviceReport = new DeviceReport { Bootloader = Encoding.UTF8.GetBytes(DeviceInfo.Build.Bootloader), Version = new byte[0], // Encoding.UTF8.GetBytes(DeviceInfo.System.OsVersion), CodeName = Encoding.UTF8.GetBytes(DeviceInfo.Build.CodeName), Incremental = Encoding.UTF8.GetBytes(DeviceInfo.Build.Incremental), Fingerprint = Encoding.UTF8.GetBytes(DeviceInfo.Build.Fingerprint), BootId = new byte[0], // Encoding.UTF8.GetBytes(DeviceInfo.BootId), AndroidId = Encoding.UTF8.GetBytes(DeviceInfo.System.AndroidId), BaseBand = Encoding.UTF8.GetBytes(DeviceInfo.Build.BaseBand), InnerVersion = Encoding.UTF8.GetBytes(DeviceInfo.Build.InnerVersion) }; MemoryStream reportData = new MemoryStream(); Serializer.Serialize(reportData, deviceReport); var passwordMd5 = new Md5Cryptor().Encrypt(Encoding.UTF8.GetBytes(password)); // 構建 tlv TlvPacker tlvs = new TlvPacker(); tlvs.PutTlv(new T18(AppInfo.appId, AppInfo.appClientVersion, uin)); tlvs.PutTlv(new T1(uin, DeviceInfo.Network.Wifi.IpAddress)); tlvs.PutTlv(new T106(AppInfo.appId, AppInfo.subAppId, AppInfo.appClientVersion, uin, new byte[4], true, passwordMd5, 0, tgtgKey, true, DeviceInfo.Guid, LoginType.Password)); tlvs.PutTlv(new T116(184024956, 66560)); tlvs.PutTlv(new T100(AppInfo.appId, AppInfo.subAppId, AppInfo.appClientVersion)); tlvs.PutTlv(new T107(0, 0, 0)); tlvs.PutTlv(new T142(AppInfo.apkPackageName)); tlvs.PutTlv(new T144(DeviceInfo.System.AndroidId, reportData.ToArray(), DeviceInfo.System.Os, DeviceInfo.System.OsVersion, DeviceInfo.Network.Type, DeviceInfo.Network.Mobile.OperatorName, DeviceInfo.Network.Wifi.ApnName, true, true, false, DeviceInfo.Guid, 285212672, DeviceInfo.System.ModelName, DeviceInfo.System.Manufacturer, tgtgKey)); tlvs.PutTlv(new T145(DeviceInfo.Guid)); tlvs.PutTlv(new T147(AppInfo.appId, AppInfo.apkVersionName, AppInfo.apkSignature)); // tlvs.PushTlv(new 166()); tlvs.PutTlv(new T154(ssoseq)); tlvs.PutTlv(new T141(DeviceInfo.Network.Mobile.OperatorName, DeviceInfo.Network.Type, DeviceInfo.Network.Wifi.ApnName)); tlvs.PutTlv(new T8()); tlvs.PutTlv(new T511(new string[] { "office.qq.com", "qun.qq.com", "gamecenter.qq.com", "docs.qq.com", "mail.qq.com", "ti.qq.com", "vip.qq.com", "tenpay.com", "qqweb.qq.com", "qzone.qq.com", "mma.qq.com", "game.qq.com", "openmobile.qq.com", "connect.qq.com", })); tlvs.PutTlv(new T187(DeviceInfo.Network.Wifi.MacAddress)); tlvs.PutTlv(new T188(DeviceInfo.System.AndroidId)); // tlvs.PushTlv(Tlv.194()); tlvs.PutTlv(new T191()); tlvs.PutTlv(new T202(DeviceInfo.Network.Wifi.ApMacAddress, DeviceInfo.Network.Wifi.Ssid)); tlvs.PutTlv(new T177(AppInfo.WtLoginSdk.buildTime, AppInfo.WtLoginSdk.sdkVersion)); tlvs.PutTlv(new T516()); tlvs.PutTlv(new T521()); tlvs.PutTlv(new T525(new T536(new byte[] { 0x01, 0x00 }))); // tlvs.PushTlv(new T544()); // tlvs.PushTlv(new T545()); PutUshortBE(subCmd); PutBytes(tlvs.GetBytes(true)); }
public DeviceReport GetInputDeviceReport(DeviceDescriptor deviceDescriptor, Guid deviceGuid) { var joystick = new Joystick(DiInstance, deviceGuid); joystick.Acquire(); var deviceReport = new DeviceReport { DeviceDescriptor = deviceDescriptor, DeviceName = $"{joystick.Information.ProductName}{(deviceDescriptor.DeviceInstance > 0 ? $" # {deviceDescriptor.DeviceInstance + 1}" : "")}", HidPath = joystick.Properties.InterfacePath }; // ----- Axes ----- if (joystick.Capabilities.AxeCount > 0) { var axisInfo = new DeviceReportNode { Title = "Axes" }; // SharpDX tells us how many axes there are, but not *which* axes. // Enumerate all possible DI axes and check to see if this stick has each axis for (var i = 0; i < Utilities.OffsetsByType[BindingType.Axis].Count; i++) { try { var offset = Utilities.OffsetsByType[BindingType.Axis][i]; // this will throw if invalid offset var deviceInfo = joystick.GetObjectInfoByName(offset // this bit will throw if the stick does not have that axis .ToString()); axisInfo.Bindings.Add(GetInputBindingReport(deviceDescriptor, new BindingDescriptor { //Index = i, Index = (int)offset, //Name = axisNames[i], Type = BindingType.Axis })); } catch { // axis does not exist } } deviceReport.Nodes.Add(axisInfo); // ----- Buttons ----- var length = joystick.Capabilities.ButtonCount; if (length > 0) { var buttonInfo = new DeviceReportNode { Title = "Buttons" }; for (var btn = 0; btn < length; btn++) { buttonInfo.Bindings.Add(GetInputBindingReport(deviceDescriptor, new BindingDescriptor { //Index = btn, Index = (int)Utilities.OffsetsByType[BindingType.Button][btn], Type = BindingType.Button })); } deviceReport.Nodes.Add(buttonInfo); } // ----- POVs ----- var povCount = joystick.Capabilities.PovCount; if (povCount > 0) { var povsInfo = new DeviceReportNode { Title = "POVs" }; for (var p = 0; p < povCount; p++) { var povInfo = new DeviceReportNode { Title = "POV #" + (p + 1), Bindings = PovBindingInfos[p] }; povsInfo.Nodes.Add(povInfo); } deviceReport.Nodes.Add(povsInfo); } } return(deviceReport); }
public async Task <IActionResult> UploadReport() { var response = new ContentResult { StatusCode = (int)HttpStatusCode.OK, ContentType = "text/plain" }; try { var newReport = new DeviceReport(); HttpRequest request = HttpContext.Request; var xs = new XmlSerializer(newReport.GetType()); newReport = (DeviceReport) xs.Deserialize(new StringReader(await new StreamReader(request.Body).ReadToEndAsync())); if (newReport == null) { response.Content = "notstats"; return(response); } var reportV2 = new DeviceReportV2(newReport); var jsonSw = new StringWriter(); jsonSw.Write(JsonConvert.SerializeObject(reportV2, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })); string reportV2String = jsonSw.ToString(); jsonSw.Close(); ctx.Reports.Add(new UploadedReport(reportV2)); ctx.SaveChanges(); var pgpIn = new MemoryStream(Encoding.UTF8.GetBytes(reportV2String)); var pgpOut = new MemoryStream(); var pgp = new ChoPGPEncryptDecrypt(); pgp.Encrypt(pgpIn, pgpOut, Path.Combine(_environment.ContentRootPath ?? throw new InvalidOperationException(), "public.asc")); pgpOut.Position = 0; reportV2String = Encoding.UTF8.GetString(pgpOut.ToArray()); var message = new MimeMessage { Subject = "New device report (old version)", Body = new TextPart("plain") { Text = reportV2String } }; message.From.Add(new MailboxAddress("DiscImageChef", "*****@*****.**")); message.To.Add(new MailboxAddress("Natalia Portillo", "*****@*****.**")); using (var client = new SmtpClient()) { client.Connect("mail.claunia.com", 25, false); client.Send(message); client.Disconnect(true); } response.Content = "ok"; return(response); } // ReSharper disable once RedundantCatchClause catch { #if DEBUG if (Debugger.IsAttached) { throw; } #endif response.Content = "error"; return(response); } }
public static void Main(string[] args) { DicConsole.WriteLineEvent += System.Console.WriteLine; DicConsole.WriteEvent += System.Console.Write; DicConsole.ErrorWriteLineEvent += System.Console.Error.WriteLine; Settings.Settings.LoadSettings(); if (Settings.Settings.Current.GdprCompliance < DicSettings.GdprLevel) { Configure.DoConfigure(true); } Statistics.LoadStats(); if (Settings.Settings.Current.Stats != null && Settings.Settings.Current.Stats.ShareStats) { Statistics.SubmitStats(); } Parser.Default.ParseArguments(args, typeof(AnalyzeOptions), typeof(BenchmarkOptions), typeof(ChecksumOptions), typeof(CompareOptions), typeof(ConfigureOptions), typeof(ConvertImageOptions), typeof(CreateSidecarOptions), typeof(DecodeOptions), typeof(DeviceInfoOptions), typeof(DeviceReportOptions), typeof(DumpMediaOptions), typeof(EntropyOptions), typeof(ExtractFilesOptions), typeof(FormatsOptions), typeof(ImageInfoOptions), typeof(ListDevicesOptions), typeof(ListEncodingsOptions), typeof(ListOptionsOptions), typeof(LsOptions), typeof(MediaInfoOptions), typeof(MediaScanOptions), typeof(PrintHexOptions), typeof(StatsOptions), typeof(VerifyOptions), typeof(GuiOptions)) .WithParsed <AnalyzeOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); Analyze.DoAnalyze(opts); }).WithParsed <CompareOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); Compare.DoCompare(opts); }).WithParsed <ChecksumOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); Checksum.DoChecksum(opts); }).WithParsed <EntropyOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); Entropy.DoEntropy(opts); }).WithParsed <VerifyOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); Verify.DoVerify(opts); }).WithParsed <PrintHexOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); Commands.PrintHex.DoPrintHex(opts); }).WithParsed <DecodeOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); Decode.DoDecode(opts); }).WithParsed <DeviceInfoOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); DeviceInfo.DoDeviceInfo(opts); }).WithParsed <MediaInfoOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); MediaInfo.DoMediaInfo(opts); }).WithParsed <MediaScanOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); MediaScan.DoMediaScan(opts); }).WithParsed <FormatsOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); Formats.ListFormats(opts); }).WithParsed <BenchmarkOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); Benchmark.DoBenchmark(opts); }).WithParsed <CreateSidecarOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); CreateSidecar.DoSidecar(opts); }).WithParsed <DumpMediaOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); DumpMedia.DoDumpMedia(opts); }).WithParsed <DeviceReportOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); DeviceReport.DoDeviceReport(opts); }).WithParsed <LsOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); Ls.DoLs(opts); }).WithParsed <ExtractFilesOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); ExtractFiles.DoExtractFiles(opts); }).WithParsed <ListDevicesOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); ListDevices.DoListDevices(opts); }).WithParsed <ListEncodingsOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); ListEncodings.DoList(); }).WithParsed <ListOptionsOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); ListOptions.DoList(); }).WithParsed <ConvertImageOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); ConvertImage.DoConvert(opts); }).WithParsed <ImageInfoOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } PrintCopyright(); ImageInfo.GetImageInfo(opts); }).WithParsed <ConfigureOptions>(opts => { PrintCopyright(); Configure.DoConfigure(false); }).WithParsed <StatsOptions>(opts => { PrintCopyright(); Commands.Statistics.ShowStats(); }).WithParsed <GuiOptions>(opts => { if (opts.Debug) { DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine; } if (opts.Verbose) { DicConsole.VerboseWriteLineEvent += System.Console.WriteLine; } new Application(Platform.Detect).Run(new frmMain(opts.Debug, opts.Verbose)); }).WithNotParsed(errs => Environment.Exit(1)); Statistics.SaveStats(); }