Split device construction per OS.

This commit is contained in:
2022-03-26 18:31:04 +00:00
parent d2d3bb560c
commit 2fa340474a
38 changed files with 1081 additions and 875 deletions

View File

@@ -56,78 +56,81 @@
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<ItemGroup>
<Compile Include="Device\DeviceException.cs"/>
<Compile Include="Device\ScsiCommands\MediaTek.cs"/>
<Compile Include="Device\ScsiCommands\MiniDisc.cs"/>
<Compile Include="Device\ScsiCommands\Optical.cs"/>
<Compile Include="Linux\Extern.cs"/>
<Compile Include="Linux\Structs.cs"/>
<Compile Include="Linux\Enums.cs"/>
<Compile Include="Enums.cs"/>
<Compile Include="Remote\Consts.cs"/>
<Compile Include="Remote\Enums.cs"/>
<Compile Include="Remote\Remote.cs"/>
<Compile Include="Remote\Structs.cs"/>
<Compile Include="Windows\Extern.cs"/>
<Compile Include="Windows\ListDevices.cs"/>
<Compile Include="Windows\Structs.cs"/>
<Compile Include="Windows\Enums.cs"/>
<Compile Include="Windows\Command.cs"/>
<Compile Include="Linux\Command.cs"/>
<Compile Include="Command.cs"/>
<Compile Include="Device\Constructor.cs"/>
<Compile Include="Device\Variables.cs"/>
<Compile Include="Device\Destructor.cs"/>
<Compile Include="Device\Commands.cs"/>
<Compile Include="Device\ScsiCommands\MMC.cs"/>
<Compile Include="Device\ScsiCommands\SPC.cs"/>
<Compile Include="Device\ScsiCommands\SBC.cs"/>
<Compile Include="Device\ScsiCommands\Pioneer.cs"/>
<Compile Include="Device\ScsiCommands\Plextor.cs"/>
<Compile Include="Device\ScsiCommands\NEC.cs"/>
<Compile Include="Device\ScsiCommands\HL-DT-ST.cs"/>
<Compile Include="Device\ScsiCommands\SSC.cs"/>
<Compile Include="Device\ScsiCommands\SMC.cs"/>
<Compile Include="Device\ScsiCommands\Adaptec.cs"/>
<Compile Include="Device\ScsiCommands\ArchiveCorp.cs"/>
<Compile Include="Device\ScsiCommands\Certance.cs"/>
<Compile Include="Device\ScsiCommands\Fujitsu.cs"/>
<Compile Include="Device\ScsiCommands\HP.cs"/>
<Compile Include="Device\ScsiCommands\Plasmon.cs"/>
<Compile Include="Device\ScsiCommands\SyQuest.cs"/>
<Compile Include="Device\AtaCommands\AtaCHS.cs"/>
<Compile Include="Device\AtaCommands\Atapi.cs"/>
<Compile Include="Device\AtaCommands\Ata28.cs"/>
<Compile Include="Device\AtaCommands\Ata48.cs"/>
<Compile Include="Device\AtaCommands\Smart.cs"/>
<Compile Include="Device\AtaCommands\Cfa.cs"/>
<Compile Include="Device\AtaCommands\MCPT.cs"/>
<Compile Include="Device\MmcCommands\MMC.cs"/>
<Compile Include="Device\MmcCommands\SecureDigital.cs"/>
<Compile Include="Device\ScsiCommands\Kreon.cs"/>
<Compile Include="Device\List.cs"/>
<Compile Include="Linux\ListDevices.cs"/>
<Compile Include="Windows\Usb.cs"/>
<Compile Include="Windows\UsbFunctions.cs"/>
<Compile Include="Device\DeviceException.cs" />
<Compile Include="Device\ScsiCommands\MediaTek.cs" />
<Compile Include="Device\ScsiCommands\MiniDisc.cs" />
<Compile Include="Device\ScsiCommands\Optical.cs" />
<Compile Include="Linux\Device.cs" />
<Compile Include="Linux\Extern.cs" />
<Compile Include="Linux\Structs.cs" />
<Compile Include="Linux\Enums.cs" />
<Compile Include="Enums.cs" />
<Compile Include="Remote\Consts.cs" />
<Compile Include="Remote\Device.cs" />
<Compile Include="Remote\Enums.cs" />
<Compile Include="Remote\Remote.cs" />
<Compile Include="Remote\Structs.cs" />
<Compile Include="Windows\Device.cs" />
<Compile Include="Windows\Extern.cs" />
<Compile Include="Windows\ListDevices.cs" />
<Compile Include="Windows\Structs.cs" />
<Compile Include="Windows\Enums.cs" />
<Compile Include="Windows\Command.cs" />
<Compile Include="Linux\Command.cs" />
<Compile Include="Command.cs" />
<Compile Include="Device\Constructor.cs" />
<Compile Include="Device\Variables.cs" />
<Compile Include="Device\Destructor.cs" />
<Compile Include="Device\Commands.cs" />
<Compile Include="Device\ScsiCommands\MMC.cs" />
<Compile Include="Device\ScsiCommands\SPC.cs" />
<Compile Include="Device\ScsiCommands\SBC.cs" />
<Compile Include="Device\ScsiCommands\Pioneer.cs" />
<Compile Include="Device\ScsiCommands\Plextor.cs" />
<Compile Include="Device\ScsiCommands\NEC.cs" />
<Compile Include="Device\ScsiCommands\HL-DT-ST.cs" />
<Compile Include="Device\ScsiCommands\SSC.cs" />
<Compile Include="Device\ScsiCommands\SMC.cs" />
<Compile Include="Device\ScsiCommands\Adaptec.cs" />
<Compile Include="Device\ScsiCommands\ArchiveCorp.cs" />
<Compile Include="Device\ScsiCommands\Certance.cs" />
<Compile Include="Device\ScsiCommands\Fujitsu.cs" />
<Compile Include="Device\ScsiCommands\HP.cs" />
<Compile Include="Device\ScsiCommands\Plasmon.cs" />
<Compile Include="Device\ScsiCommands\SyQuest.cs" />
<Compile Include="Device\AtaCommands\AtaCHS.cs" />
<Compile Include="Device\AtaCommands\Atapi.cs" />
<Compile Include="Device\AtaCommands\Ata28.cs" />
<Compile Include="Device\AtaCommands\Ata48.cs" />
<Compile Include="Device\AtaCommands\Smart.cs" />
<Compile Include="Device\AtaCommands\Cfa.cs" />
<Compile Include="Device\AtaCommands\MCPT.cs" />
<Compile Include="Device\MmcCommands\MMC.cs" />
<Compile Include="Device\MmcCommands\SecureDigital.cs" />
<Compile Include="Device\ScsiCommands\Kreon.cs" />
<Compile Include="Device\List.cs" />
<Compile Include="Linux\ListDevices.cs" />
<Compile Include="Windows\Usb.cs" />
<Compile Include="Windows\UsbFunctions.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="System.Management" Version="6.0.0"/>
<PackageReference Include="Unclassified.NetRevisionTask" Version="0.4.2" PrivateAssets="all"/>
<PackageReference Include="System.Management" Version="6.0.0" />
<PackageReference Include="Unclassified.NetRevisionTask" Version="0.4.2" PrivateAssets="all" />
</ItemGroup>
<ProjectExtensions>
<MonoDevelop>
<Properties>
<Policies>
<DotNetNamingPolicy DirectoryNamespaceAssociation="PrefixedHierarchical" ResourceNamePolicy="MSBuild"/>
<StandardHeader IncludeInNewFiles="True" Text="/***************************************************************************&#xA;Aaru Data Preservation Suite&#xA;----------------------------------------------------------------------------&#xA; &#xA;Filename : ${FileName}&#xA;Author(s) : ${AuthorName} &lt;${AuthorEmail}&gt;&#xA;&#xA;Component : Component&#xA; &#xA;--[ Description ] ----------------------------------------------------------&#xA; &#xA; Description&#xA; &#xA;--[ License ] --------------------------------------------------------------&#xA; &#xA; This library is free software; you can redistribute it and/or modify&#xA; it under the terms of the GNU Lesser General Public License as&#xA; published by the Free Software Foundation; either version 2.1 of the&#xA; License, or (at your option) any later version.&#xA;&#xA; This library is distributed in the hope that it will be useful, but&#xA; WITHOUT ANY WARRANTY; without even the implied warranty of&#xA; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU&#xA; Lesser General Public License for more details.&#xA;&#xA; You should have received a copy of the GNU Lesser General Public&#xA; License along with this library; if not, see &lt;http://www.gnu.org/licenses/&gt;.&#xA;&#xA;----------------------------------------------------------------------------&#xA;Copyright © 2011-${Year} ${CopyrightHolder}&#xA;****************************************************************************/"/>
<TextStylePolicy FileWidth="120" TabWidth="4" IndentWidth="4" RemoveTrailingWhitespace="True" NoTabsAfterNonTabs="False" EolMarker="Native" TabsToSpaces="True" scope="text/x-csharp"/>
<CSharpFormattingPolicy IndentBlock="True" IndentBraces="False" IndentSwitchSection="True" IndentSwitchCaseSection="True" LabelPositioning="OneLess" NewLinesForBracesInTypes="True" NewLinesForBracesInMethods="True" NewLinesForBracesInProperties="True" NewLinesForBracesInAccessors="True" NewLinesForBracesInAnonymousMethods="True" NewLinesForBracesInControlBlocks="True" NewLinesForBracesInAnonymousTypes="True" NewLinesForBracesInObjectCollectionArrayInitializers="True" NewLinesForBracesInLambdaExpressionBody="True" NewLineForElse="True" NewLineForCatch="True" NewLineForFinally="True" NewLineForMembersInObjectInit="True" NewLineForMembersInAnonymousTypes="True" NewLineForClausesInQuery="True" SpacingAfterMethodDeclarationName="False" SpaceWithinMethodDeclarationParenthesis="False" SpaceBetweenEmptyMethodDeclarationParentheses="False" SpaceAfterMethodCallName="False" SpaceWithinMethodCallParentheses="False" SpaceBetweenEmptyMethodCallParentheses="False" SpaceWithinExpressionParentheses="False" SpaceWithinCastParentheses="False" SpaceWithinOtherParentheses="False" SpaceAfterCast="False" SpacesIgnoreAroundVariableDeclaration="False" SpaceBeforeOpenSquareBracket="False" SpaceBetweenEmptySquareBrackets="False" SpaceWithinSquareBrackets="False" SpaceAfterColonInBaseTypeDeclaration="True" SpaceAfterComma="True" SpaceAfterDot="False" SpaceAfterSemicolonsInForStatement="True" SpaceBeforeColonInBaseTypeDeclaration="True" SpaceBeforeComma="False" SpaceBeforeDot="False" SpaceBeforeSemicolonsInForStatement="False" SpacingAroundBinaryOperator="Single" WrappingPreserveSingleLine="True" WrappingKeepStatementsOnSingleLine="True" SpaceAfterControlFlowStatementKeyword="False" scope="text/x-csharp"/>
<DotNetNamingPolicy DirectoryNamespaceAssociation="PrefixedHierarchical" ResourceNamePolicy="MSBuild" />
<StandardHeader IncludeInNewFiles="True" Text="/***************************************************************************&#xA;Aaru Data Preservation Suite&#xA;----------------------------------------------------------------------------&#xA; &#xA;Filename : ${FileName}&#xA;Author(s) : ${AuthorName} &lt;${AuthorEmail}&gt;&#xA;&#xA;Component : Component&#xA; &#xA;--[ Description ] ----------------------------------------------------------&#xA; &#xA; Description&#xA; &#xA;--[ License ] --------------------------------------------------------------&#xA; &#xA; This library is free software; you can redistribute it and/or modify&#xA; it under the terms of the GNU Lesser General Public License as&#xA; published by the Free Software Foundation; either version 2.1 of the&#xA; License, or (at your option) any later version.&#xA;&#xA; This library is distributed in the hope that it will be useful, but&#xA; WITHOUT ANY WARRANTY; without even the implied warranty of&#xA; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU&#xA; Lesser General Public License for more details.&#xA;&#xA; You should have received a copy of the GNU Lesser General Public&#xA; License along with this library; if not, see &lt;http://www.gnu.org/licenses/&gt;.&#xA;&#xA;----------------------------------------------------------------------------&#xA;Copyright © 2011-${Year} ${CopyrightHolder}&#xA;****************************************************************************/" />
<TextStylePolicy FileWidth="120" TabWidth="4" IndentWidth="4" RemoveTrailingWhitespace="True" NoTabsAfterNonTabs="False" EolMarker="Native" TabsToSpaces="True" scope="text/x-csharp" />
<CSharpFormattingPolicy IndentBlock="True" IndentBraces="False" IndentSwitchSection="True" IndentSwitchCaseSection="True" LabelPositioning="OneLess" NewLinesForBracesInTypes="True" NewLinesForBracesInMethods="True" NewLinesForBracesInProperties="True" NewLinesForBracesInAccessors="True" NewLinesForBracesInAnonymousMethods="True" NewLinesForBracesInControlBlocks="True" NewLinesForBracesInAnonymousTypes="True" NewLinesForBracesInObjectCollectionArrayInitializers="True" NewLinesForBracesInLambdaExpressionBody="True" NewLineForElse="True" NewLineForCatch="True" NewLineForFinally="True" NewLineForMembersInObjectInit="True" NewLineForMembersInAnonymousTypes="True" NewLineForClausesInQuery="True" SpacingAfterMethodDeclarationName="False" SpaceWithinMethodDeclarationParenthesis="False" SpaceBetweenEmptyMethodDeclarationParentheses="False" SpaceAfterMethodCallName="False" SpaceWithinMethodCallParentheses="False" SpaceBetweenEmptyMethodCallParentheses="False" SpaceWithinExpressionParentheses="False" SpaceWithinCastParentheses="False" SpaceWithinOtherParentheses="False" SpaceAfterCast="False" SpacesIgnoreAroundVariableDeclaration="False" SpaceBeforeOpenSquareBracket="False" SpaceBetweenEmptySquareBrackets="False" SpaceWithinSquareBrackets="False" SpaceAfterColonInBaseTypeDeclaration="True" SpaceAfterComma="True" SpaceAfterDot="False" SpaceAfterSemicolonsInForStatement="True" SpaceBeforeColonInBaseTypeDeclaration="True" SpaceBeforeComma="False" SpaceBeforeDot="False" SpaceBeforeSemicolonsInForStatement="False" SpacingAroundBinaryOperator="Single" WrappingPreserveSingleLine="True" WrappingKeepStatementsOnSingleLine="True" SpaceAfterControlFlowStatementKeyword="False" scope="text/x-csharp" />
</Policies>
</Properties>
</MonoDevelop>
</ProjectExtensions>
<ItemGroup>
<ProjectReference Include="..\Aaru.CommonTypes\Aaru.CommonTypes.csproj"/>
<ProjectReference Include="..\Aaru.CommonTypes\Aaru.CommonTypes.csproj" />
<ProjectReference Include="..\Aaru.Console\Aaru.Console.csproj"></ProjectReference>
<ProjectReference Include="..\Aaru.Decoders\Aaru.Decoders.csproj"></ProjectReference>
<ProjectReference Include="..\Aaru.Helpers\Aaru.Helpers.csproj"></ProjectReference>

View File

@@ -36,7 +36,7 @@ using System;
using Aaru.Console;
using Aaru.Decoders.ATA;
public sealed partial class Device
public partial class Device
{
/// <summary>Reads the drive buffer using PIO transfer</summary>
/// <param name="buffer">Buffer that contains the read data</param>

View File

@@ -36,7 +36,7 @@ using System;
using Aaru.Console;
using Aaru.Decoders.ATA;
public sealed partial class Device
public partial class Device
{
/// <summary>Gets native max address using 48-bit addressing</summary>
/// <param name="lba">Maximum addressable block</param>

View File

@@ -36,7 +36,7 @@ using System;
using Aaru.Console;
using Aaru.Decoders.ATA;
public sealed partial class Device
public partial class Device
{
/// <summary>Sends the ATA IDENTIFY DEVICE command to the device, using default device timeout</summary>
/// <returns><c>true</c> if the command failed and <paramref name="statusRegisters" /> contains the error registers.</returns>

View File

@@ -35,7 +35,7 @@ namespace Aaru.Devices;
using Aaru.Console;
using Aaru.Decoders.ATA;
public sealed partial class Device
public partial class Device
{
/// <summary>Sends the ATA IDENTIFY PACKET DEVICE command to the device, using default device timeout</summary>
/// <returns><c>true</c> if the command failed and <paramref name="statusRegisters" /> contains the error registers.</returns>

View File

@@ -36,7 +36,7 @@ using System;
using Aaru.Console;
using Aaru.Decoders.ATA;
public sealed partial class Device
public partial class Device
{
/// <summary>Requests to translate an LBA to a card physical address</summary>
/// <param name="buffer">Data buffer</param>

View File

@@ -36,7 +36,7 @@ using System;
using Aaru.Console;
using Aaru.Decoders.ATA;
public sealed partial class Device
public partial class Device
{
/// <summary>Enables media card pass through</summary>
/// <param name="statusRegisters">Status registers.</param>

View File

@@ -36,7 +36,7 @@ using System;
using Aaru.Console;
using Aaru.Decoders.ATA;
public sealed partial class Device
public partial class Device
{
/// <summary>Disables S.M.A.R.T.</summary>
/// <param name="statusRegisters">Returned status registers</param>

View File

@@ -37,7 +37,7 @@ using System.Diagnostics.CodeAnalysis;
using Aaru.Decoders.ATA;
[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")]
public sealed partial class Device
public partial class Device
{
/// <summary>Sends a SCSI command to this device</summary>
/// <returns>0 if no error occurred, otherwise, errno</returns>

View File

@@ -34,47 +34,25 @@ namespace Aaru.Devices;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using Aaru.CommonTypes.Enums;
using Aaru.CommonTypes.Interop;
using Aaru.CommonTypes.Structs.Devices.ATA;
using Aaru.CommonTypes.Structs.Devices.SCSI;
using Aaru.Decoders.SCSI;
using Aaru.Decoders.SCSI.MMC;
using Aaru.Decoders.SecureDigital;
using Aaru.Devices.Linux;
using Aaru.Devices.Windows;
using Aaru.Helpers;
using Microsoft.Win32.SafeHandles;
using Extern = Aaru.Devices.Windows.Extern;
using FileAccess = Aaru.Devices.Windows.FileAccess;
using FileAttributes = Aaru.Devices.Windows.FileAttributes;
using FileMode = Aaru.Devices.Windows.FileMode;
using FileShare = Aaru.Devices.Windows.FileShare;
using Inquiry = Aaru.CommonTypes.Structs.Devices.SCSI.Inquiry;
using Marshal = System.Runtime.InteropServices.Marshal;
using PlatformID = Aaru.CommonTypes.Interop.PlatformID;
using VendorString = Aaru.Decoders.SecureDigital.VendorString;
/// <summary>Implements a device or media containing drive</summary>
[SuppressMessage("ReSharper", "MemberCanBePrivate.Global"), SuppressMessage("ReSharper", "UnusedMember.Global"),
SuppressMessage("ReSharper", "UnusedMethodReturnValue.Global")]
public sealed partial class Device
public partial class Device
{
/// <summary>Opens the device for sending direct commands</summary>
/// <param name="devicePath">Device path</param>
public static Device Create(string devicePath)
{
var dev = new Device();
dev.PlatformId = DetectOS.GetRealPlatformID();
dev.Timeout = 15;
dev.Error = false;
dev.IsRemovable = false;
dev._devicePath = devicePath;
Device dev = null;
Uri aaruUri;
try
@@ -83,686 +61,24 @@ public sealed partial class Device
}
catch(Exception)
{
// Ignore, treat as local path below
aaruUri = null;
return null;
}
if(aaruUri?.Scheme is "dic" or "aaru")
if(aaruUri.Scheme is "dic" or "aaru")
dev = Remote.Device.Create(aaruUri);
else if(OperatingSystem.IsLinux())
dev = Linux.Device.Create(devicePath);
else if(OperatingSystem.IsWindows())
dev = Windows.Device.Create(devicePath);
if(dev is null)
throw new DeviceException("Platform not supported.");
if(dev.Type == DeviceType.SCSI ||
dev.Type == DeviceType.ATAPI)
{
devicePath = aaruUri.AbsolutePath;
dev.ScsiInquiry(out byte[] inqBuf, out _);
if(devicePath.StartsWith('/'))
devicePath = devicePath.Substring(1);
if(devicePath.StartsWith("dev", StringComparison.Ordinal))
devicePath = $"/{devicePath}";
dev._remote = new Remote.Remote(aaruUri);
dev.Error = !dev._remote.Open(devicePath, out int errno);
dev.LastError = errno;
}
else
switch(dev.PlatformId)
{
case PlatformID.Win32NT:
{
dev.FileHandle = Extern.CreateFile(devicePath, FileAccess.GenericRead | FileAccess.GenericWrite,
FileShare.Read | FileShare.Write, IntPtr.Zero,
FileMode.OpenExisting, FileAttributes.Normal, IntPtr.Zero);
if(((SafeFileHandle)dev.FileHandle).IsInvalid)
{
dev.Error = true;
dev.LastError = Marshal.GetLastWin32Error();
}
break;
}
case PlatformID.Linux:
{
dev.FileHandle =
Linux.Extern.open(devicePath,
FileFlags.ReadWrite | FileFlags.NonBlocking | FileFlags.CreateNew);
if((int)dev.FileHandle < 0)
{
dev.LastError = Marshal.GetLastWin32Error();
if(dev.LastError is 13 or 30) // EACCES or EROFS
{
dev.FileHandle = Linux.Extern.open(devicePath, FileFlags.Readonly | FileFlags.NonBlocking);
if((int)dev.FileHandle < 0)
{
dev.Error = true;
dev.LastError = Marshal.GetLastWin32Error();
}
}
else
dev.Error = true;
dev.LastError = Marshal.GetLastWin32Error();
}
break;
}
default: throw new DeviceException($"Platform {dev.PlatformId} not supported.");
}
if(dev.Error)
throw new DeviceException(dev.LastError);
// Seems ioctl(2) does not allow the atomicity needed
if(dev._remote is null)
{
if(dev.PlatformId == PlatformID.Linux)
_readMultipleBlockCannotSetBlockCount = true;
}
else if(dev._remote.ServerOperatingSystem == "Linux")
_readMultipleBlockCannotSetBlockCount = true;
dev.Type = DeviceType.Unknown;
dev.ScsiType = PeripheralDeviceTypes.UnknownDevice;
byte[] ataBuf;
byte[] inqBuf = null;
if(dev.Error)
throw new DeviceException(dev.LastError);
var scsiSense = true;
if(dev._remote is null)
// Windows is answering SCSI INQUIRY for all device types so it needs to be detected first
switch(dev.PlatformId)
{
case PlatformID.Win32NT:
var query = new StoragePropertyQuery();
query.PropertyId = StoragePropertyId.Device;
query.QueryType = StorageQueryType.Standard;
query.AdditionalParameters = new byte[1];
IntPtr descriptorPtr = Marshal.AllocHGlobal(1000);
var descriptorB = new byte[1000];
uint returned = 0;
var error = 0;
bool hasError = !Extern.DeviceIoControlStorageQuery((SafeFileHandle)dev.FileHandle,
WindowsIoctl.IoctlStorageQueryProperty,
ref query, (uint)Marshal.SizeOf(query),
descriptorPtr, 1000, ref returned, IntPtr.Zero);
if(hasError)
error = Marshal.GetLastWin32Error();
Marshal.Copy(descriptorPtr, descriptorB, 0, 1000);
if(!hasError &&
error == 0)
{
var descriptor = new StorageDeviceDescriptor
{
Version = BitConverter.ToUInt32(descriptorB, 0),
Size = BitConverter.ToUInt32(descriptorB, 4),
DeviceType = descriptorB[8],
DeviceTypeModifier = descriptorB[9],
RemovableMedia = descriptorB[10] > 0,
CommandQueueing = descriptorB[11] > 0,
VendorIdOffset = BitConverter.ToInt32(descriptorB, 12),
ProductIdOffset = BitConverter.ToInt32(descriptorB, 16),
ProductRevisionOffset = BitConverter.ToInt32(descriptorB, 20),
SerialNumberOffset = BitConverter.ToInt32(descriptorB, 24),
BusType = (StorageBusType)BitConverter.ToUInt32(descriptorB, 28),
RawPropertiesLength = BitConverter.ToUInt32(descriptorB, 32)
};
descriptor.RawDeviceProperties = new byte[descriptor.RawPropertiesLength];
Array.Copy(descriptorB, 36, descriptor.RawDeviceProperties, 0, descriptor.RawPropertiesLength);
switch(descriptor.BusType)
{
case StorageBusType.SCSI:
case StorageBusType.SSA:
case StorageBusType.Fibre:
case StorageBusType.iSCSI:
case StorageBusType.SAS:
dev.Type = DeviceType.SCSI;
break;
case StorageBusType.FireWire:
dev.IsFireWire = true;
dev.Type = DeviceType.SCSI;
break;
case StorageBusType.USB:
dev.IsUsb = true;
dev.Type = DeviceType.SCSI;
break;
case StorageBusType.ATAPI:
dev.Type = DeviceType.ATAPI;
break;
case StorageBusType.ATA:
case StorageBusType.SATA:
dev.Type = DeviceType.ATA;
break;
case StorageBusType.MultiMediaCard:
dev.Type = DeviceType.MMC;
break;
case StorageBusType.SecureDigital:
dev.Type = DeviceType.SecureDigital;
break;
case StorageBusType.NVMe:
dev.Type = DeviceType.NVMe;
break;
}
switch(dev.Type)
{
case DeviceType.SCSI:
case DeviceType.ATAPI:
scsiSense = dev.ScsiInquiry(out inqBuf, out _);
break;
case DeviceType.ATA:
bool atapiSense = dev.AtapiIdentify(out ataBuf, out _);
if(!atapiSense)
{
dev.Type = DeviceType.ATAPI;
Identify.IdentifyDevice? ataid = Identify.Decode(ataBuf);
if(ataid.HasValue)
scsiSense = dev.ScsiInquiry(out inqBuf, out _);
}
else
dev.Manufacturer = "ATA";
break;
}
}
Marshal.FreeHGlobal(descriptorPtr);
if(Windows.Command.IsSdhci((SafeFileHandle)dev.FileHandle))
{
var sdBuffer = new byte[16];
dev.LastError = Windows.Command.SendMmcCommand((SafeFileHandle)dev.FileHandle,
MmcCommands.SendCsd, false, false,
MmcFlags.ResponseSpiR2 | MmcFlags.ResponseR2 |
MmcFlags.CommandAc, 0, 16, 1, ref sdBuffer,
out _, out _, out bool sense);
if(!sense)
{
dev._cachedCsd = new byte[16];
Array.Copy(sdBuffer, 0, dev._cachedCsd, 0, 16);
}
sdBuffer = new byte[16];
dev.LastError = Windows.Command.SendMmcCommand((SafeFileHandle)dev.FileHandle,
MmcCommands.SendCid, false, false,
MmcFlags.ResponseSpiR2 | MmcFlags.ResponseR2 |
MmcFlags.CommandAc, 0, 16, 1, ref sdBuffer,
out _, out _, out sense);
if(!sense)
{
dev._cachedCid = new byte[16];
Array.Copy(sdBuffer, 0, dev._cachedCid, 0, 16);
}
sdBuffer = new byte[8];
dev.LastError = Windows.Command.SendMmcCommand((SafeFileHandle)dev.FileHandle,
(MmcCommands)SecureDigitalCommands.SendScr,
false, true,
MmcFlags.ResponseSpiR1 | MmcFlags.ResponseR1 |
MmcFlags.CommandAdtc, 0, 8, 1, ref sdBuffer,
out _, out _, out sense);
if(!sense)
{
dev._cachedScr = new byte[8];
Array.Copy(sdBuffer, 0, dev._cachedScr, 0, 8);
}
sdBuffer = new byte[4];
dev.LastError = Windows.Command.SendMmcCommand((SafeFileHandle)dev.FileHandle,
dev._cachedScr != null
? (MmcCommands)SecureDigitalCommands.
SendOperatingCondition
: MmcCommands.SendOpCond, false, true,
MmcFlags.ResponseSpiR3 | MmcFlags.ResponseR3 |
MmcFlags.CommandBcr, 0, 4, 1, ref sdBuffer,
out _, out _, out sense);
if(!sense)
{
dev._cachedScr = new byte[4];
Array.Copy(sdBuffer, 0, dev._cachedScr, 0, 4);
}
}
break;
case PlatformID.Linux:
if(devicePath.StartsWith("/dev/sd", StringComparison.Ordinal) ||
devicePath.StartsWith("/dev/sr", StringComparison.Ordinal) ||
devicePath.StartsWith("/dev/st", StringComparison.Ordinal) ||
devicePath.StartsWith("/dev/sg", StringComparison.Ordinal))
scsiSense = dev.ScsiInquiry(out inqBuf, out _);
// MultiMediaCard and SecureDigital go here
else if(devicePath.StartsWith("/dev/mmcblk", StringComparison.Ordinal))
{
string devPath = devicePath.Substring(5);
if(File.Exists("/sys/block/" + devPath + "/device/csd"))
{
int len = ConvertFromFileHexAscii("/sys/block/" + devPath + "/device/csd",
out dev._cachedCsd);
if(len == 0)
dev._cachedCsd = null;
}
if(File.Exists("/sys/block/" + devPath + "/device/cid"))
{
int len = ConvertFromFileHexAscii("/sys/block/" + devPath + "/device/cid",
out dev._cachedCid);
if(len == 0)
dev._cachedCid = null;
}
if(File.Exists("/sys/block/" + devPath + "/device/scr"))
{
int len = ConvertFromFileHexAscii("/sys/block/" + devPath + "/device/scr",
out dev._cachedScr);
if(len == 0)
dev._cachedScr = null;
}
if(File.Exists("/sys/block/" + devPath + "/device/ocr"))
{
int len = ConvertFromFileHexAscii("/sys/block/" + devPath + "/device/ocr",
out dev._cachedOcr);
if(len == 0)
dev._cachedOcr = null;
}
}
break;
default:
scsiSense = dev.ScsiInquiry(out inqBuf, out _);
break;
}
else
{
dev.Type = dev._remote.GetDeviceType();
switch(dev.Type)
{
case DeviceType.ATAPI:
case DeviceType.SCSI:
scsiSense = dev.ScsiInquiry(out inqBuf, out _);
break;
case DeviceType.SecureDigital:
case DeviceType.MMC:
if(!dev._remote.GetSdhciRegisters(out dev._cachedCsd, out dev._cachedCid, out dev._cachedOcr,
out dev._cachedScr))
{
dev.Type = DeviceType.SCSI;
dev.ScsiType = PeripheralDeviceTypes.DirectAccess;
}
break;
}
}
#region SecureDigital / MultiMediaCard
if(dev._cachedCid != null)
{
dev.ScsiType = PeripheralDeviceTypes.DirectAccess;
dev.IsRemovable = false;
if(dev._cachedScr != null)
{
dev.Type = DeviceType.SecureDigital;
CID decoded = Decoders.DecodeCID(dev._cachedCid);
dev.Manufacturer = VendorString.Prettify(decoded.Manufacturer);
dev.Model = decoded.ProductName;
dev.FirmwareRevision =
$"{(decoded.ProductRevision & 0xF0) >> 4:X2}.{decoded.ProductRevision & 0x0F:X2}";
dev.Serial = $"{decoded.ProductSerialNumber}";
}
else
{
dev.Type = DeviceType.MMC;
Aaru.Decoders.MMC.CID decoded = Aaru.Decoders.MMC.Decoders.DecodeCID(dev._cachedCid);
dev.Manufacturer = Aaru.Decoders.MMC.VendorString.Prettify(decoded.Manufacturer);
dev.Model = decoded.ProductName;
dev.FirmwareRevision =
$"{(decoded.ProductRevision & 0xF0) >> 4:X2}.{decoded.ProductRevision & 0x0F:X2}";
dev.Serial = $"{decoded.ProductSerialNumber}";
}
return dev;
}
#endregion SecureDigital / MultiMediaCard
#region USB
if(dev._remote is null)
switch(dev.PlatformId)
{
case PlatformID.Linux:
if(devicePath.StartsWith("/dev/sd", StringComparison.Ordinal) ||
devicePath.StartsWith("/dev/sr", StringComparison.Ordinal) ||
devicePath.StartsWith("/dev/st", StringComparison.Ordinal))
{
string devPath = devicePath.Substring(5);
if(Directory.Exists("/sys/block/" + devPath))
{
string resolvedLink = Linux.Command.ReadLink("/sys/block/" + devPath);
if(!string.IsNullOrEmpty(resolvedLink))
{
resolvedLink = "/sys" + resolvedLink.Substring(2);
while(resolvedLink.Contains("usb"))
{
resolvedLink = Path.GetDirectoryName(resolvedLink);
if(!File.Exists(resolvedLink + "/descriptors") ||
!File.Exists(resolvedLink + "/idProduct") ||
!File.Exists(resolvedLink + "/idVendor"))
continue;
var usbFs = new FileStream(resolvedLink + "/descriptors", System.IO.FileMode.Open,
System.IO.FileAccess.Read);
var usbBuf = new byte[65536];
int usbCount = usbFs.Read(usbBuf, 0, 65536);
dev.UsbDescriptors = new byte[usbCount];
Array.Copy(usbBuf, 0, dev.UsbDescriptors, 0, usbCount);
usbFs.Close();
var usbSr = new StreamReader(resolvedLink + "/idProduct");
string usbTemp = usbSr.ReadToEnd();
ushort.TryParse(usbTemp, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
out dev._usbProduct);
usbSr.Close();
usbSr = new StreamReader(resolvedLink + "/idVendor");
usbTemp = usbSr.ReadToEnd();
ushort.TryParse(usbTemp, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
out dev._usbVendor);
usbSr.Close();
if(File.Exists(resolvedLink + "/manufacturer"))
{
usbSr = new StreamReader(resolvedLink + "/manufacturer");
dev.UsbManufacturerString = usbSr.ReadToEnd().Trim();
usbSr.Close();
}
if(File.Exists(resolvedLink + "/product"))
{
usbSr = new StreamReader(resolvedLink + "/product");
dev.UsbProductString = usbSr.ReadToEnd().Trim();
usbSr.Close();
}
if(File.Exists(resolvedLink + "/serial"))
{
usbSr = new StreamReader(resolvedLink + "/serial");
dev.UsbSerialString = usbSr.ReadToEnd().Trim();
usbSr.Close();
}
dev.IsUsb = true;
break;
}
}
}
}
break;
case PlatformID.Win32NT:
Usb.UsbDevice usbDevice = null;
// I have to search for USB disks, floppies and CD-ROMs as separate device types
foreach(string devGuid in new[]
{
Usb.GUID_DEVINTERFACE_FLOPPY, Usb.GUID_DEVINTERFACE_CDROM, Usb.GUID_DEVINTERFACE_DISK,
Usb.GUID_DEVINTERFACE_TAPE
})
{
usbDevice = Usb.FindDrivePath(devicePath, devGuid);
if(usbDevice != null)
break;
}
if(usbDevice != null)
{
dev.UsbDescriptors = usbDevice.BinaryDescriptors;
dev._usbVendor = (ushort)usbDevice._deviceDescriptor.idVendor;
dev._usbProduct = (ushort)usbDevice._deviceDescriptor.idProduct;
dev.UsbManufacturerString = usbDevice.Manufacturer;
dev.UsbProductString = usbDevice.Product;
dev.UsbSerialString =
usbDevice.SerialNumber; // This is incorrect filled by Windows with SCSI/ATA serial number
}
break;
default:
dev.IsUsb = false;
break;
}
else
{
if(dev._remote.GetUsbData(out byte[] remoteUsbDescriptors, out ushort remoteUsbVendor,
out ushort remoteUsbProduct, out string remoteUsbManufacturer,
out string remoteUsbProductString, out string remoteUsbSerial))
{
dev.IsUsb = true;
dev.UsbDescriptors = remoteUsbDescriptors;
dev._usbVendor = remoteUsbVendor;
dev._usbProduct = remoteUsbProduct;
dev.UsbManufacturerString = remoteUsbManufacturer;
dev.UsbProductString = remoteUsbProductString;
dev.UsbSerialString = remoteUsbSerial;
}
}
#endregion USB
#region FireWire
if(!(dev._remote is null))
{
if(dev._remote.GetFireWireData(out dev._firewireVendor, out dev._firewireModel, out dev._firewireGuid,
out string remoteFireWireVendorName, out string remoteFireWireModelName))
{
dev.IsFireWire = true;
dev.FireWireVendorName = remoteFireWireVendorName;
dev.FireWireModelName = remoteFireWireModelName;
}
}
else
{
if(dev.PlatformId == PlatformID.Linux)
{
if(devicePath.StartsWith("/dev/sd", StringComparison.Ordinal) ||
devicePath.StartsWith("/dev/sr", StringComparison.Ordinal) ||
devicePath.StartsWith("/dev/st", StringComparison.Ordinal))
{
string devPath = devicePath.Substring(5);
if(Directory.Exists("/sys/block/" + devPath))
{
string resolvedLink = Linux.Command.ReadLink("/sys/block/" + devPath);
resolvedLink = "/sys" + resolvedLink.Substring(2);
if(!string.IsNullOrEmpty(resolvedLink))
while(resolvedLink.Contains("firewire"))
{
resolvedLink = Path.GetDirectoryName(resolvedLink);
if(!File.Exists(resolvedLink + "/model") ||
!File.Exists(resolvedLink + "/vendor") ||
!File.Exists(resolvedLink + "/guid"))
continue;
var fwSr = new StreamReader(resolvedLink + "/model");
string fwTemp = fwSr.ReadToEnd();
uint.TryParse(fwTemp, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
out dev._firewireModel);
fwSr.Close();
fwSr = new StreamReader(resolvedLink + "/vendor");
fwTemp = fwSr.ReadToEnd();
uint.TryParse(fwTemp, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
out dev._firewireVendor);
fwSr.Close();
fwSr = new StreamReader(resolvedLink + "/guid");
fwTemp = fwSr.ReadToEnd();
ulong.TryParse(fwTemp, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
out dev._firewireGuid);
fwSr.Close();
if(File.Exists(resolvedLink + "/model_name"))
{
fwSr = new StreamReader(resolvedLink + "/model_name");
dev.FireWireModelName = fwSr.ReadToEnd().Trim();
fwSr.Close();
}
if(File.Exists(resolvedLink + "/vendor_name"))
{
fwSr = new StreamReader(resolvedLink + "/vendor_name");
dev.FireWireVendorName = fwSr.ReadToEnd().Trim();
fwSr.Close();
}
dev.IsFireWire = true;
break;
}
}
}
}
// TODO: Implement for other operating systems
else
dev.IsFireWire = false;
}
#endregion FireWire
#region PCMCIA
if(dev._remote is null)
{
if(dev.PlatformId == PlatformID.Linux)
{
if(devicePath.StartsWith("/dev/sd", StringComparison.Ordinal) ||
devicePath.StartsWith("/dev/sr", StringComparison.Ordinal) ||
devicePath.StartsWith("/dev/st", StringComparison.Ordinal))
{
string devPath = devicePath.Substring(5);
if(Directory.Exists("/sys/block/" + devPath))
{
string resolvedLink = Linux.Command.ReadLink("/sys/block/" + devPath);
resolvedLink = "/sys" + resolvedLink.Substring(2);
if(!string.IsNullOrEmpty(resolvedLink))
while(resolvedLink.Contains("/sys/devices"))
{
resolvedLink = Path.GetDirectoryName(resolvedLink);
if(!Directory.Exists(resolvedLink + "/pcmcia_socket"))
continue;
string[] subdirs = Directory.GetDirectories(resolvedLink + "/pcmcia_socket",
"pcmcia_socket*",
SearchOption.TopDirectoryOnly);
if(subdirs.Length <= 0)
continue;
string possibleDir = Path.Combine(resolvedLink, "pcmcia_socket", subdirs[0]);
if(!File.Exists(possibleDir + "/card_type") ||
!File.Exists(possibleDir + "/cis"))
continue;
var cisFs = new FileStream(possibleDir + "/cis", System.IO.FileMode.Open,
System.IO.FileAccess.Read);
var cisBuf = new byte[65536];
int cisCount = cisFs.Read(cisBuf, 0, 65536);
dev.Cis = new byte[cisCount];
Array.Copy(cisBuf, 0, dev.Cis, 0, cisCount);
cisFs.Close();
dev.IsPcmcia = true;
break;
}
}
}
}
// TODO: Implement for other operating systems
else
dev.IsPcmcia = false;
}
else
{
if(dev._remote.GetPcmciaData(out byte[] cisBuf))
{
dev.IsPcmcia = true;
dev.Cis = cisBuf;
}
}
#endregion PCMCIA
if(!scsiSense)
{
Inquiry? inquiry = Inquiry.Decode(inqBuf);
dev.Type = DeviceType.SCSI;
@@ -793,7 +109,7 @@ public sealed partial class Device
dev.ScsiType = (PeripheralDeviceTypes)inquiry.Value.PeripheralDeviceType;
}
bool atapiSense = dev.AtapiIdentify(out ataBuf, out _);
bool atapiSense = dev.AtapiIdentify(out byte[] ataBuf, out _);
if(!atapiSense)
{
@@ -808,10 +124,10 @@ public sealed partial class Device
dev.Error = false;
}
if(scsiSense && !(dev.IsUsb || dev.IsFireWire) ||
if(dev.Type != DeviceType.SCSI && dev.Type != DeviceType.ATAPI && !(dev.IsUsb || dev.IsFireWire) ||
dev.Manufacturer == "ATA")
{
bool ataSense = dev.AtaIdentify(out ataBuf, out _);
bool ataSense = dev.AtaIdentify(out byte[] ataBuf, out _);
if(!ataSense)
{
@@ -910,17 +226,5 @@ public sealed partial class Device
return dev;
}
Device() {}
static int ConvertFromFileHexAscii(string file, out byte[] outBuf)
{
var sr = new StreamReader(file);
string ins = sr.ReadToEnd().Trim();
int count = Helpers.Marshal.ConvertFromHexAscii(ins, out outBuf);
sr.Close();
return count;
}
protected Device() {}
}

View File

@@ -32,11 +32,7 @@
namespace Aaru.Devices;
using Aaru.CommonTypes.Interop;
using Aaru.Devices.Linux;
using Microsoft.Win32.SafeHandles;
public sealed partial class Device
public partial class Device
{
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the <see cref="Device" /> is
@@ -45,31 +41,5 @@ public sealed partial class Device
~Device() => Close();
/// <summary>Closes a device</summary>
public void Close()
{
if(_remote != null)
{
_remote.Close();
_remote.Disconnect();
return;
}
if(FileHandle == null)
return;
switch(PlatformId)
{
case PlatformID.Win32NT:
(FileHandle as SafeFileHandle)?.Close();
break;
case PlatformID.Linux:
Extern.close((int)FileHandle);
break;
}
FileHandle = null;
}
public virtual void Close() {}
}

View File

@@ -73,7 +73,7 @@ public struct DeviceInfo
public readonly byte[] Padding;
}
public sealed partial class Device
public partial class Device
{
/// <summary>Lists devices attached to current machine</summary>
/// <returns>List of devices</returns>

View File

@@ -35,7 +35,7 @@ namespace Aaru.Devices;
using System;
using Aaru.Console;
public sealed partial class Device
public partial class Device
{
/// <summary>Reads the CSD register from a SecureDigital or MultiMediaCard device</summary>
/// <param name="buffer">Data buffer</param>
@@ -206,7 +206,7 @@ public sealed partial class Device
return sense;
}
static bool _readMultipleBlockCannotSetBlockCount;
protected static bool _readMultipleBlockCannotSetBlockCount;
/// <summary>Reads multiple blocks from a SecureDigital or MultiMediaCard device</summary>
/// <param name="buffer">Data buffer</param>

View File

@@ -34,7 +34,7 @@ namespace Aaru.Devices;
using Aaru.Console;
public sealed partial class Device
public partial class Device
{
/// <summary>Reads the status register from a SecureDigital device</summary>
/// <param name="buffer">Data buffer</param>

View File

@@ -36,7 +36,7 @@ namespace Aaru.Devices;
using System;
using Aaru.Console;
public sealed partial class Device
public partial class Device
{
/// <summary>Gets the underlying drive cylinder, head and index bytes for the specified SCSI LBA.</summary>
/// <param name="buffer">Buffer.</param>

View File

@@ -35,7 +35,7 @@ namespace Aaru.Devices;
using System;
using Aaru.Console;
public sealed partial class Device
public partial class Device
{
/// <summary>Gets the underlying drive cylinder, head and index bytes for the specified SCSI LBA.</summary>
/// <param name="buffer">Buffer.</param>

View File

@@ -37,7 +37,7 @@ using System.Diagnostics.CodeAnalysis;
using Aaru.Console;
[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")]
public sealed partial class Device
public partial class Device
{
/// <summary>Parks the load arm in preparation for transport</summary>
/// <param name="senseBuffer">Sense buffer.</param>

View File

@@ -37,7 +37,7 @@ using System.Text;
using Aaru.Console;
using Aaru.Helpers;
public sealed partial class Device
public partial class Device
{
/// <summary>Sets the data for the integrated display</summary>
/// <param name="senseBuffer">Returned SENSE buffer</param>

View File

@@ -34,7 +34,7 @@ namespace Aaru.Devices;
using Aaru.Console;
public sealed partial class Device
public partial class Device
{
/// <summary>Reads a "raw" sector from DVD on HL-DT-ST drives.</summary>
/// <returns><c>true</c> if the command failed and <paramref name="senseBuffer" /> contains the sense buffer.</returns>

View File

@@ -34,7 +34,7 @@ namespace Aaru.Devices;
using Aaru.Console;
public sealed partial class Device
public partial class Device
{
/// <summary>Sends the HP READ LONG vendor command</summary>
/// <returns><c>true</c> if the command failed and <paramref name="senseBuffer" /> contains the sense buffer.</returns>

View File

@@ -35,7 +35,7 @@ namespace Aaru.Devices;
using System;
using Aaru.Console;
public sealed partial class Device
public partial class Device
{
/// <summary>Sets the drive to the xtreme unlocked state</summary>
/// <returns><c>true</c> if the command failed and <paramref name="senseBuffer" /> contains the sense buffer.</returns>

View File

@@ -37,7 +37,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Text;
using Aaru.Console;
public sealed partial class Device
public partial class Device
{
/// <summary>Sends the MMC GET CONFIGURATION command for all Features</summary>
/// <returns><c>true</c> if the command failed and <paramref name="senseBuffer" /> contains the sense buffer.</returns>

View File

@@ -34,7 +34,7 @@ namespace Aaru.Devices;
using Aaru.Console;
public sealed partial class Device
public partial class Device
{
/// <summary>Reads from the drive's DRAM.</summary>
/// <returns><c>true</c> if the command failed and <paramref name="senseBuffer" /> contains the sense buffer.</returns>

View File

@@ -39,7 +39,7 @@ namespace Aaru.Devices;
using System;
using Aaru.Console;
public sealed partial class Device
public partial class Device
{
/// <summary>Reads the data TOC from an MD-DATA</summary>
/// <param name="buffer">Buffer where the response will be stored</param>

View File

@@ -34,7 +34,7 @@ namespace Aaru.Devices;
using Aaru.Console;
public sealed partial class Device
public partial class Device
{
/// <summary>Sends the NEC READ CD-DA command</summary>
/// <returns><c>true</c> if the command failed and <paramref name="senseBuffer" /> contains the sense buffer.</returns>

View File

@@ -36,7 +36,7 @@ using System;
using Aaru.Console;
using Aaru.Decoders.SCSI;
public sealed partial class Device
public partial class Device
{
/// <summary>Scan the medium for a contiguous set of written or blank logical blocks</summary>
/// <param name="senseBuffer">Sense buffer.</param>

View File

@@ -34,7 +34,7 @@ namespace Aaru.Devices;
using Aaru.Console;
public sealed partial class Device
public partial class Device
{
/// <summary>Sends the Pioneer READ CD-DA command</summary>
/// <returns><c>true</c> if the command failed and <paramref name="senseBuffer" /> contains the sense buffer.</returns>

View File

@@ -34,7 +34,7 @@ namespace Aaru.Devices;
using Aaru.Console;
public sealed partial class Device
public partial class Device
{
/// <summary>Sends the Plasmon READ LONG vendor command</summary>
/// <returns><c>true</c> if the command failed and <paramref name="senseBuffer" /> contains the sense buffer.</returns>

View File

@@ -35,7 +35,7 @@ namespace Aaru.Devices;
using Aaru.Console;
using Aaru.Helpers;
public sealed partial class Device
public partial class Device
{
/// <summary>Sends the Plextor READ CD-DA command</summary>
/// <returns><c>true</c> if the command failed and <paramref name="senseBuffer" /> contains the sense buffer.</returns>

View File

@@ -35,7 +35,7 @@ namespace Aaru.Devices;
using System;
using Aaru.Console;
public sealed partial class Device
public partial class Device
{
/// <summary>Sends the SBC READ (6) command</summary>
/// <returns><c>true</c> if the command failed and <paramref name="senseBuffer" /> contains the sense buffer.</returns>

View File

@@ -34,7 +34,7 @@ namespace Aaru.Devices;
using Aaru.Console;
public sealed partial class Device
public partial class Device
{
/// <summary>Reads an attribute from the medium auxiliary memory, or reports which elements in the changer contain one</summary>
/// <param name="buffer">Buffer.</param>

View File

@@ -38,7 +38,7 @@ using Aaru.Console;
using PlatformID = Aaru.CommonTypes.Interop.PlatformID;
[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")]
public sealed partial class Device
public partial class Device
{
/// <summary>Sends the SPC INQUIRY command to the device using default device timeout.</summary>
/// <returns><c>true</c> if the command failed and <paramref name="senseBuffer" /> contains the sense buffer.</returns>

View File

@@ -35,7 +35,7 @@ namespace Aaru.Devices;
using System;
using Aaru.Console;
public sealed partial class Device
public partial class Device
{
/// <summary>Prepares the medium for reading</summary>
/// <returns><c>true</c>, if load was successful, <c>false</c> otherwise.</returns>

View File

@@ -35,7 +35,7 @@ namespace Aaru.Devices;
using System;
using Aaru.Console;
public sealed partial class Device
public partial class Device
{
/// <summary>Sends the SyQuest READ (6) command</summary>
/// <returns><c>true</c> if the command failed and <paramref name="senseBuffer" /> contains the sense buffer.</returns>

View File

@@ -36,28 +36,28 @@ using Aaru.CommonTypes.Enums;
using Aaru.CommonTypes.Interop;
using Aaru.CommonTypes.Structs.Devices.SCSI;
public sealed partial class Device
public partial class Device
{
ushort _usbVendor;
ushort _usbProduct;
ulong _firewireGuid;
uint _firewireModel;
uint _firewireVendor;
private protected ushort _usbVendor;
private protected ushort _usbProduct;
private protected ulong _firewireGuid;
private protected uint _firewireModel;
private protected uint _firewireVendor;
// MMC and SecureDigital, values that need to be get with card idle, something that may
// not be possible to do but usually is already done by the SDHCI driver.
byte[] _cachedCsd;
byte[] _cachedCid;
byte[] _cachedScr;
byte[] _cachedOcr;
private protected byte[] _cachedCsd;
private protected byte[] _cachedCid;
private protected byte[] _cachedScr;
private protected byte[] _cachedOcr;
/// <summary>Gets the Platform ID for this device</summary>
/// <value>The Platform ID</value>
public PlatformID PlatformId { get; private set; }
public PlatformID PlatformId { get; private protected set; }
/// <summary>Gets the file handle representing this device</summary>
/// <value>The file handle</value>
public object FileHandle { get; private set; }
public object FileHandle { get; private protected set; }
/// <summary>Gets or sets the standard timeout for commands sent to this device</summary>
/// <value>The timeout in seconds</value>
@@ -65,43 +65,43 @@ public sealed partial class Device
/// <summary>Gets a value indicating whether this <see cref="Device" /> is in error.</summary>
/// <value><c>true</c> if error; otherwise, <c>false</c>.</value>
public bool Error { get; private set; }
public bool Error { get; private protected set; }
/// <summary>Gets the last error number.</summary>
/// <value>The last error.</value>
public int LastError { get; private set; }
public int LastError { get; private protected set; }
/// <summary>Gets the device type.</summary>
/// <value>The device type.</value>
public DeviceType Type { get; private set; }
public DeviceType Type { get; private protected set; }
/// <summary>Gets the device's manufacturer</summary>
/// <value>The manufacturer.</value>
public string Manufacturer { get; private set; }
public string Manufacturer { get; private protected set; }
/// <summary>Gets the device model</summary>
/// <value>The model.</value>
public string Model { get; private set; }
public string Model { get; private protected set; }
/// <summary>Gets the device's firmware version.</summary>
/// <value>The firmware version.</value>
public string FirmwareRevision { get; private set; }
public string FirmwareRevision { get; private protected set; }
/// <summary>Gets the device's serial number.</summary>
/// <value>The serial number.</value>
public string Serial { get; private set; }
public string Serial { get; private protected set; }
/// <summary>Gets the device's SCSI peripheral device type</summary>
/// <value>The SCSI peripheral device type.</value>
public PeripheralDeviceTypes ScsiType { get; private set; }
public PeripheralDeviceTypes ScsiType { get; private protected set; }
/// <summary>Gets a value indicating whether this device's media is removable.</summary>
/// <value><c>true</c> if this device's media is removable; otherwise, <c>false</c>.</value>
public bool IsRemovable { get; private set; }
public bool IsRemovable { get; private protected set; }
/// <summary>Gets a value indicating whether this device is attached via USB.</summary>
/// <value><c>true</c> if this device is attached via USB; otherwise, <c>false</c>.</value>
public bool IsUsb { get; private set; }
public bool IsUsb { get; private protected set; }
/// <summary>Gets the USB vendor ID.</summary>
/// <value>The USB vendor ID.</value>
@@ -113,23 +113,23 @@ public sealed partial class Device
/// <summary>Gets the USB descriptors.</summary>
/// <value>The USB descriptors.</value>
public byte[] UsbDescriptors { get; private set; }
public byte[] UsbDescriptors { get; private protected set; }
/// <summary>Gets the USB manufacturer string.</summary>
/// <value>The USB manufacturer string.</value>
public string UsbManufacturerString { get; private set; }
public string UsbManufacturerString { get; private protected set; }
/// <summary>Gets the USB product string.</summary>
/// <value>The USB product string.</value>
public string UsbProductString { get; private set; }
public string UsbProductString { get; private protected set; }
/// <summary>Gets the USB serial string.</summary>
/// <value>The USB serial string.</value>
public string UsbSerialString { get; private set; }
public string UsbSerialString { get; private protected set; }
/// <summary>Gets a value indicating whether this device is attached via FireWire.</summary>
/// <value><c>true</c> if this device is attached via FireWire; otherwise, <c>false</c>.</value>
public bool IsFireWire { get; private set; }
public bool IsFireWire { get; private protected set; }
/// <summary>Gets the FireWire GUID</summary>
/// <value>The FireWire GUID.</value>
@@ -141,7 +141,7 @@ public sealed partial class Device
/// <summary>Gets the FireWire model name.</summary>
/// <value>The FireWire model name.</value>
public string FireWireModelName { get; private set; }
public string FireWireModelName { get; private protected set; }
/// <summary>Gets the FireWire vendor number.</summary>
/// <value>The FireWire vendor number.</value>
@@ -149,7 +149,7 @@ public sealed partial class Device
/// <summary>Gets the FireWire vendor name.</summary>
/// <value>The FireWire vendor name.</value>
public string FireWireVendorName { get; private set; }
public string FireWireVendorName { get; private protected set; }
/// <summary>Gets a value indicating whether this device is a CompactFlash device.</summary>
/// <value><c>true</c> if this device is a CompactFlash device; otherwise, <c>false</c>.</value>
@@ -157,14 +157,14 @@ public sealed partial class Device
/// <summary>Gets a value indicating whether this device is a PCMCIA device.</summary>
/// <value><c>true</c> if this device is a PCMCIA device; otherwise, <c>false</c>.</value>
public bool IsPcmcia { get; private set; }
public bool IsPcmcia { get; private protected set; }
/// <summary>Contains the PCMCIA CIS if applicable</summary>
public byte[] Cis { get; private set; }
public byte[] Cis { get; private protected set; }
Remote.Remote _remote;
private protected Remote.Remote _remote;
bool? _isRemoteAdmin;
string _devicePath;
private protected string _devicePath;
/// <summary>Returns if remote is running under administrative (aka root) privileges</summary>
public bool IsRemoteAdmin

View File

@@ -0,0 +1,409 @@
// /***************************************************************************
// Aaru Data Preservation Suite
// ----------------------------------------------------------------------------
//
// Filename : Device.cs
// Author(s) : Natalia Portillo <claunia@claunia.com>
//
// Component : Linux direct device access.
//
// --[ Description ] ----------------------------------------------------------
//
// Prepares a Linux device for direct access.
//
// --[ License ] --------------------------------------------------------------
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, see <http://www.gnu.org/licenses/>.
//
// ----------------------------------------------------------------------------
// Copyright © 2011-2022 Natalia Portillo
// ****************************************************************************/
namespace Aaru.Devices.Linux;
using System;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Aaru.CommonTypes.Enums;
using Aaru.CommonTypes.Interop;
using Aaru.CommonTypes.Structs.Devices.SCSI;
using Aaru.Decoders.SecureDigital;
using PlatformID = Aaru.CommonTypes.Interop.PlatformID;
using VendorString = Aaru.Decoders.MMC.VendorString;
/// <inheritdoc />
[SupportedOSPlatform("linux")]
public class Device : Devices.Device
{
Device() {}
public new static Device Create(string devicePath)
{
var dev = new Device
{
PlatformId = DetectOS.GetRealPlatformID(),
Timeout = 15,
Error = false,
IsRemovable = false
};
dev.FileHandle = Extern.open(devicePath, FileFlags.ReadWrite | FileFlags.NonBlocking | FileFlags.CreateNew);
if((int)dev.FileHandle < 0)
{
dev.LastError = Marshal.GetLastWin32Error();
if(dev.LastError is 13 or 30) // EACCES or EROFS
{
dev.FileHandle = Extern.open(devicePath, FileFlags.Readonly | FileFlags.NonBlocking);
if((int)dev.FileHandle < 0)
{
dev.Error = true;
dev.LastError = Marshal.GetLastWin32Error();
}
}
else
dev.Error = true;
dev.LastError = Marshal.GetLastWin32Error();
}
if(dev.Error)
throw new DeviceException(dev.LastError);
// Seems ioctl(2) does not allow the atomicity needed
if(dev.PlatformId == PlatformID.Linux)
_readMultipleBlockCannotSetBlockCount = true;
dev.Type = DeviceType.Unknown;
dev.ScsiType = PeripheralDeviceTypes.UnknownDevice;
byte[] ataBuf;
byte[] inqBuf = null;
if(dev.Error)
throw new DeviceException(dev.LastError);
if(devicePath.StartsWith("/dev/sd", StringComparison.Ordinal) ||
devicePath.StartsWith("/dev/sr", StringComparison.Ordinal) ||
devicePath.StartsWith("/dev/st", StringComparison.Ordinal) ||
devicePath.StartsWith("/dev/sg", StringComparison.Ordinal))
if(!dev.ScsiInquiry(out inqBuf, out _))
dev.Type = DeviceType.SCSI;
// MultiMediaCard and SecureDigital go here
else if(devicePath.StartsWith("/dev/mmcblk", StringComparison.Ordinal))
{
string devPath = devicePath.Substring(5);
if(File.Exists("/sys/block/" + devPath + "/device/csd"))
{
int len = ConvertFromFileHexAscii("/sys/block/" + devPath + "/device/csd", out dev._cachedCsd);
if(len == 0)
dev._cachedCsd = null;
}
if(File.Exists("/sys/block/" + devPath + "/device/cid"))
{
int len = ConvertFromFileHexAscii("/sys/block/" + devPath + "/device/cid", out dev._cachedCid);
if(len == 0)
dev._cachedCid = null;
}
if(File.Exists("/sys/block/" + devPath + "/device/scr"))
{
int len = ConvertFromFileHexAscii("/sys/block/" + devPath + "/device/scr", out dev._cachedScr);
if(len == 0)
dev._cachedScr = null;
}
if(File.Exists("/sys/block/" + devPath + "/device/ocr"))
{
int len = ConvertFromFileHexAscii("/sys/block/" + devPath + "/device/ocr", out dev._cachedOcr);
if(len == 0)
dev._cachedOcr = null;
}
}
#region SecureDigital / MultiMediaCard
if(dev._cachedCid != null)
{
dev.ScsiType = PeripheralDeviceTypes.DirectAccess;
dev.IsRemovable = false;
if(dev._cachedScr != null)
{
dev.Type = DeviceType.SecureDigital;
CID decoded = Decoders.DecodeCID(dev._cachedCid);
dev.Manufacturer = VendorString.Prettify(decoded.Manufacturer);
dev.Model = decoded.ProductName;
dev.FirmwareRevision =
$"{(decoded.ProductRevision & 0xF0) >> 4:X2}.{decoded.ProductRevision & 0x0F:X2}";
dev.Serial = $"{decoded.ProductSerialNumber}";
}
else
{
dev.Type = DeviceType.MMC;
Aaru.Decoders.MMC.CID decoded = Aaru.Decoders.MMC.Decoders.DecodeCID(dev._cachedCid);
dev.Manufacturer = VendorString.Prettify(decoded.Manufacturer);
dev.Model = decoded.ProductName;
dev.FirmwareRevision =
$"{(decoded.ProductRevision & 0xF0) >> 4:X2}.{decoded.ProductRevision & 0x0F:X2}";
dev.Serial = $"{decoded.ProductSerialNumber}";
}
return dev;
}
#endregion SecureDigital / MultiMediaCard
#region USB
if(devicePath.StartsWith("/dev/sd", StringComparison.Ordinal) ||
devicePath.StartsWith("/dev/sr", StringComparison.Ordinal) ||
devicePath.StartsWith("/dev/st", StringComparison.Ordinal))
{
string devPath = devicePath.Substring(5);
if(Directory.Exists("/sys/block/" + devPath))
{
string resolvedLink = Command.ReadLink("/sys/block/" + devPath);
if(!string.IsNullOrEmpty(resolvedLink))
{
resolvedLink = "/sys" + resolvedLink.Substring(2);
while(resolvedLink.Contains("usb"))
{
resolvedLink = Path.GetDirectoryName(resolvedLink);
if(!File.Exists(resolvedLink + "/descriptors") ||
!File.Exists(resolvedLink + "/idProduct") ||
!File.Exists(resolvedLink + "/idVendor"))
continue;
var usbFs = new FileStream(resolvedLink + "/descriptors", FileMode.Open, FileAccess.Read);
var usbBuf = new byte[65536];
int usbCount = usbFs.Read(usbBuf, 0, 65536);
dev.UsbDescriptors = new byte[usbCount];
Array.Copy(usbBuf, 0, dev.UsbDescriptors, 0, usbCount);
usbFs.Close();
var usbSr = new StreamReader(resolvedLink + "/idProduct");
string usbTemp = usbSr.ReadToEnd();
ushort.TryParse(usbTemp, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
out dev._usbProduct);
usbSr.Close();
usbSr = new StreamReader(resolvedLink + "/idVendor");
usbTemp = usbSr.ReadToEnd();
ushort.TryParse(usbTemp, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
out dev._usbVendor);
usbSr.Close();
if(File.Exists(resolvedLink + "/manufacturer"))
{
usbSr = new StreamReader(resolvedLink + "/manufacturer");
dev.UsbManufacturerString = usbSr.ReadToEnd().Trim();
usbSr.Close();
}
if(File.Exists(resolvedLink + "/product"))
{
usbSr = new StreamReader(resolvedLink + "/product");
dev.UsbProductString = usbSr.ReadToEnd().Trim();
usbSr.Close();
}
if(File.Exists(resolvedLink + "/serial"))
{
usbSr = new StreamReader(resolvedLink + "/serial");
dev.UsbSerialString = usbSr.ReadToEnd().Trim();
usbSr.Close();
}
dev.IsUsb = true;
break;
}
}
}
}
#endregion USB
#region FireWire
{
if(true)
{
if(devicePath.StartsWith("/dev/sd", StringComparison.Ordinal) ||
devicePath.StartsWith("/dev/sr", StringComparison.Ordinal) ||
devicePath.StartsWith("/dev/st", StringComparison.Ordinal))
{
string devPath = devicePath.Substring(5);
if(Directory.Exists("/sys/block/" + devPath))
{
string resolvedLink = Command.ReadLink("/sys/block/" + devPath);
resolvedLink = "/sys" + resolvedLink.Substring(2);
if(!string.IsNullOrEmpty(resolvedLink))
while(resolvedLink.Contains("firewire"))
{
resolvedLink = Path.GetDirectoryName(resolvedLink);
if(!File.Exists(resolvedLink + "/model") ||
!File.Exists(resolvedLink + "/vendor") ||
!File.Exists(resolvedLink + "/guid"))
continue;
var fwSr = new StreamReader(resolvedLink + "/model");
string fwTemp = fwSr.ReadToEnd();
uint.TryParse(fwTemp, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
out dev._firewireModel);
fwSr.Close();
fwSr = new StreamReader(resolvedLink + "/vendor");
fwTemp = fwSr.ReadToEnd();
uint.TryParse(fwTemp, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
out dev._firewireVendor);
fwSr.Close();
fwSr = new StreamReader(resolvedLink + "/guid");
fwTemp = fwSr.ReadToEnd();
ulong.TryParse(fwTemp, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
out dev._firewireGuid);
fwSr.Close();
if(File.Exists(resolvedLink + "/model_name"))
{
fwSr = new StreamReader(resolvedLink + "/model_name");
dev.FireWireModelName = fwSr.ReadToEnd().Trim();
fwSr.Close();
}
if(File.Exists(resolvedLink + "/vendor_name"))
{
fwSr = new StreamReader(resolvedLink + "/vendor_name");
dev.FireWireVendorName = fwSr.ReadToEnd().Trim();
fwSr.Close();
}
dev.IsFireWire = true;
break;
}
}
}
}
// TODO: Implement for other operating systems
else
dev.IsFireWire = false;
}
#endregion FireWire
#region PCMCIA
if(devicePath.StartsWith("/dev/sd", StringComparison.Ordinal) ||
devicePath.StartsWith("/dev/sr", StringComparison.Ordinal) ||
devicePath.StartsWith("/dev/st", StringComparison.Ordinal))
{
string devPath = devicePath.Substring(5);
if(Directory.Exists("/sys/block/" + devPath))
{
string resolvedLink = Command.ReadLink("/sys/block/" + devPath);
resolvedLink = "/sys" + resolvedLink.Substring(2);
if(!string.IsNullOrEmpty(resolvedLink))
while(resolvedLink.Contains("/sys/devices"))
{
resolvedLink = Path.GetDirectoryName(resolvedLink);
if(!Directory.Exists(resolvedLink + "/pcmcia_socket"))
continue;
string[] subdirs = Directory.GetDirectories(resolvedLink + "/pcmcia_socket", "pcmcia_socket*",
SearchOption.TopDirectoryOnly);
if(subdirs.Length <= 0)
continue;
string possibleDir = Path.Combine(resolvedLink, "pcmcia_socket", subdirs[0]);
if(!File.Exists(possibleDir + "/card_type") ||
!File.Exists(possibleDir + "/cis"))
continue;
var cisFs = new FileStream(possibleDir + "/cis", FileMode.Open, FileAccess.Read);
var cisBuf = new byte[65536];
int cisCount = cisFs.Read(cisBuf, 0, 65536);
dev.Cis = new byte[cisCount];
Array.Copy(cisBuf, 0, dev.Cis, 0, cisCount);
cisFs.Close();
dev.IsPcmcia = true;
break;
}
}
}
#endregion PCMCIA
return dev;
}
static int ConvertFromFileHexAscii(string file, out byte[] outBuf)
{
var sr = new StreamReader(file);
string ins = sr.ReadToEnd().Trim();
int count = Helpers.Marshal.ConvertFromHexAscii(ins, out outBuf);
sr.Close();
return count;
}
/// <inheritdoc />
public override void Close()
{
if(FileHandle == null)
return;
Extern.close((int)FileHandle);
FileHandle = null;
}
}

View File

@@ -0,0 +1,192 @@
// /***************************************************************************
// Aaru Data Preservation Suite
// ----------------------------------------------------------------------------
//
// Filename : Device.cs
// Author(s) : Natalia Portillo <claunia@claunia.com>
//
// Component : Remote device access.
//
// --[ Description ] ----------------------------------------------------------
//
// Prepares a remote device for direct access.
//
// --[ License ] --------------------------------------------------------------
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, see <http://www.gnu.org/licenses/>.
//
// ----------------------------------------------------------------------------
// Copyright © 2011-2022 Natalia Portillo
// ****************************************************************************/
namespace Aaru.Devices.Remote;
using System;
using Aaru.CommonTypes.Enums;
using Aaru.CommonTypes.Interop;
using Aaru.CommonTypes.Structs.Devices.SCSI;
using Aaru.Decoders.SecureDigital;
/// <inheritdoc />
public sealed class Device : Devices.Device
{
Device() {}
/// <summary>Opens the device for sending direct commands</summary>
/// <param name="aaruUri">AaruRemote URI</param>
/// <returns>Device</returns>
public static Device Create(Uri aaruUri)
{
var dev = new Device
{
PlatformId = DetectOS.GetRealPlatformID(),
Timeout = 15,
Error = false,
IsRemovable = false
};
if(aaruUri.Scheme is not ("dic" or "aaru"))
return null;
string devicePath = aaruUri.AbsolutePath;
if(devicePath.StartsWith('/'))
devicePath = devicePath[1..];
if(devicePath.StartsWith("dev", StringComparison.Ordinal))
devicePath = $"/{devicePath}";
dev._devicePath = devicePath;
dev._remote = new Remote(aaruUri);
dev.Error = !dev._remote.Open(devicePath, out int errno);
dev.LastError = errno;
if(dev.Error)
throw new DeviceException(dev.LastError);
if(dev._remote.ServerOperatingSystem == "Linux")
_readMultipleBlockCannotSetBlockCount = true;
dev.Type = DeviceType.Unknown;
dev.ScsiType = PeripheralDeviceTypes.UnknownDevice;
byte[] ataBuf;
byte[] inqBuf = null;
if(dev.Error)
throw new DeviceException(dev.LastError);
dev.Type = dev._remote.GetDeviceType();
switch(dev.Type)
{
case DeviceType.ATAPI:
case DeviceType.SCSI:
bool scsiSense = dev.ScsiInquiry(out inqBuf, out _);
break;
case DeviceType.SecureDigital:
case DeviceType.MMC:
if(!dev._remote.GetSdhciRegisters(out dev._cachedCsd, out dev._cachedCid, out dev._cachedOcr,
out dev._cachedScr))
{
dev.Type = DeviceType.SCSI;
dev.ScsiType = PeripheralDeviceTypes.DirectAccess;
}
break;
}
#region SecureDigital / MultiMediaCard
if(dev._cachedCid != null)
{
dev.ScsiType = PeripheralDeviceTypes.DirectAccess;
dev.IsRemovable = false;
if(dev._cachedScr != null)
{
dev.Type = DeviceType.SecureDigital;
CID decoded = Decoders.DecodeCID(dev._cachedCid);
dev.Manufacturer = VendorString.Prettify(decoded.Manufacturer);
dev.Model = decoded.ProductName;
dev.FirmwareRevision =
$"{(decoded.ProductRevision & 0xF0) >> 4:X2}.{decoded.ProductRevision & 0x0F:X2}";
dev.Serial = $"{decoded.ProductSerialNumber}";
}
else
{
dev.Type = DeviceType.MMC;
Aaru.Decoders.MMC.CID decoded = Aaru.Decoders.MMC.Decoders.DecodeCID(dev._cachedCid);
dev.Manufacturer = Aaru.Decoders.MMC.VendorString.Prettify(decoded.Manufacturer);
dev.Model = decoded.ProductName;
dev.FirmwareRevision =
$"{(decoded.ProductRevision & 0xF0) >> 4:X2}.{decoded.ProductRevision & 0x0F:X2}";
dev.Serial = $"{decoded.ProductSerialNumber}";
}
return dev;
}
#endregion SecureDigital / MultiMediaCard
#region USB
if(dev._remote.GetUsbData(out byte[] remoteUsbDescriptors, out ushort remoteUsbVendor,
out ushort remoteUsbProduct, out string remoteUsbManufacturer,
out string remoteUsbProductString, out string remoteUsbSerial))
{
dev.IsUsb = true;
dev.UsbDescriptors = remoteUsbDescriptors;
dev._usbVendor = remoteUsbVendor;
dev._usbProduct = remoteUsbProduct;
dev.UsbManufacturerString = remoteUsbManufacturer;
dev.UsbProductString = remoteUsbProductString;
dev.UsbSerialString = remoteUsbSerial;
}
#endregion USB
#region FireWire
if(dev._remote.GetFireWireData(out dev._firewireVendor, out dev._firewireModel, out dev._firewireGuid,
out string remoteFireWireVendorName, out string remoteFireWireModelName))
{
dev.IsFireWire = true;
dev.FireWireVendorName = remoteFireWireVendorName;
dev.FireWireModelName = remoteFireWireModelName;
}
#endregion FireWire
#region PCMCIA
if(dev._remote.GetPcmciaData(out byte[] cisBuf))
{
dev.IsPcmcia = true;
dev.Cis = cisBuf;
}
#endregion PCMCIA
return dev;
}
/// <inheritdoc />
public override void Close()
{
if(_remote == null)
return;
_remote.Close();
_remote.Disconnect();
}
}

View File

@@ -0,0 +1,328 @@
// /***************************************************************************
// Aaru Data Preservation Suite
// ----------------------------------------------------------------------------
//
// Filename : Device.cs
// Author(s) : Natalia Portillo <claunia@claunia.com>
//
// Component : Windows direct device access.
//
// --[ Description ] ----------------------------------------------------------
//
// Prepares a Windows device for direct access.
//
// --[ License ] --------------------------------------------------------------
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, see <http://www.gnu.org/licenses/>.
//
// ----------------------------------------------------------------------------
// Copyright © 2011-2022 Natalia Portillo
// ****************************************************************************/
namespace Aaru.Devices.Windows;
using System;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Aaru.CommonTypes.Enums;
using Aaru.CommonTypes.Interop;
using Aaru.CommonTypes.Structs.Devices.SCSI;
using Aaru.Decoders.SecureDigital;
using Microsoft.Win32.SafeHandles;
/// <inheritdoc />
[SupportedOSPlatform("windows")]
public class Device : Devices.Device
{
Device() {}
public new static Device Create(string devicePath)
{
var dev = new Device
{
PlatformId = DetectOS.GetRealPlatformID(),
Timeout = 15,
Error = false,
IsRemovable = false
};
dev.FileHandle = Extern.CreateFile(devicePath, FileAccess.GenericRead | FileAccess.GenericWrite,
FileShare.Read | FileShare.Write, IntPtr.Zero, FileMode.OpenExisting,
FileAttributes.Normal, IntPtr.Zero);
if(((SafeFileHandle)dev.FileHandle).IsInvalid)
{
dev.Error = true;
dev.LastError = Marshal.GetLastWin32Error();
}
if(dev.Error)
throw new DeviceException(dev.LastError);
dev.Type = DeviceType.Unknown;
dev.ScsiType = PeripheralDeviceTypes.UnknownDevice;
byte[] ataBuf;
byte[] inqBuf = null;
if(dev.Error)
throw new DeviceException(dev.LastError);
// Windows is answering SCSI INQUIRY for all device types so it needs to be detected first
var query = new StoragePropertyQuery();
query.PropertyId = StoragePropertyId.Device;
query.QueryType = StorageQueryType.Standard;
query.AdditionalParameters = new byte[1];
IntPtr descriptorPtr = Marshal.AllocHGlobal(1000);
var descriptorB = new byte[1000];
uint returned = 0;
var error = 0;
bool hasError = !Extern.DeviceIoControlStorageQuery((SafeFileHandle)dev.FileHandle,
WindowsIoctl.IoctlStorageQueryProperty, ref query,
(uint)Marshal.SizeOf(query), descriptorPtr, 1000,
ref returned, IntPtr.Zero);
if(hasError)
error = Marshal.GetLastWin32Error();
Marshal.Copy(descriptorPtr, descriptorB, 0, 1000);
if(!hasError &&
error == 0)
{
var descriptor = new StorageDeviceDescriptor
{
Version = BitConverter.ToUInt32(descriptorB, 0),
Size = BitConverter.ToUInt32(descriptorB, 4),
DeviceType = descriptorB[8],
DeviceTypeModifier = descriptorB[9],
RemovableMedia = descriptorB[10] > 0,
CommandQueueing = descriptorB[11] > 0,
VendorIdOffset = BitConverter.ToInt32(descriptorB, 12),
ProductIdOffset = BitConverter.ToInt32(descriptorB, 16),
ProductRevisionOffset = BitConverter.ToInt32(descriptorB, 20),
SerialNumberOffset = BitConverter.ToInt32(descriptorB, 24),
BusType = (StorageBusType)BitConverter.ToUInt32(descriptorB, 28),
RawPropertiesLength = BitConverter.ToUInt32(descriptorB, 32)
};
descriptor.RawDeviceProperties = new byte[descriptor.RawPropertiesLength];
Array.Copy(descriptorB, 36, descriptor.RawDeviceProperties, 0, descriptor.RawPropertiesLength);
switch(descriptor.BusType)
{
case StorageBusType.SCSI:
case StorageBusType.SSA:
case StorageBusType.Fibre:
case StorageBusType.iSCSI:
case StorageBusType.SAS:
dev.Type = DeviceType.SCSI;
break;
case StorageBusType.FireWire:
dev.IsFireWire = true;
dev.Type = DeviceType.SCSI;
break;
case StorageBusType.USB:
dev.IsUsb = true;
dev.Type = DeviceType.SCSI;
break;
case StorageBusType.ATAPI:
dev.Type = DeviceType.ATAPI;
break;
case StorageBusType.ATA:
case StorageBusType.SATA:
dev.Type = DeviceType.ATA;
break;
case StorageBusType.MultiMediaCard:
dev.Type = DeviceType.MMC;
break;
case StorageBusType.SecureDigital:
dev.Type = DeviceType.SecureDigital;
break;
case StorageBusType.NVMe:
dev.Type = DeviceType.NVMe;
break;
}
switch(dev.Type)
{
case DeviceType.ATA:
bool atapiSense = dev.AtapiIdentify(out ataBuf, out _);
if(!atapiSense)
dev.Type = DeviceType.ATAPI;
else
dev.Manufacturer = "ATA";
break;
}
}
Marshal.FreeHGlobal(descriptorPtr);
if(Command.IsSdhci((SafeFileHandle)dev.FileHandle))
{
var sdBuffer = new byte[16];
dev.LastError = Command.SendMmcCommand((SafeFileHandle)dev.FileHandle, MmcCommands.SendCsd, false, false,
MmcFlags.ResponseSpiR2 | MmcFlags.ResponseR2 | MmcFlags.CommandAc, 0,
16, 1, ref sdBuffer, out _, out _, out bool sense);
if(!sense)
{
dev._cachedCsd = new byte[16];
Array.Copy(sdBuffer, 0, dev._cachedCsd, 0, 16);
}
sdBuffer = new byte[16];
dev.LastError = Command.SendMmcCommand((SafeFileHandle)dev.FileHandle, MmcCommands.SendCid, false, false,
MmcFlags.ResponseSpiR2 | MmcFlags.ResponseR2 | MmcFlags.CommandAc, 0,
16, 1, ref sdBuffer, out _, out _, out sense);
if(!sense)
{
dev._cachedCid = new byte[16];
Array.Copy(sdBuffer, 0, dev._cachedCid, 0, 16);
}
sdBuffer = new byte[8];
dev.LastError = Command.SendMmcCommand((SafeFileHandle)dev.FileHandle,
(MmcCommands)SecureDigitalCommands.SendScr, false, true,
MmcFlags.ResponseSpiR1 | MmcFlags.ResponseR1 | MmcFlags.CommandAdtc,
0, 8, 1, ref sdBuffer, out _, out _, out sense);
if(!sense)
{
dev._cachedScr = new byte[8];
Array.Copy(sdBuffer, 0, dev._cachedScr, 0, 8);
}
sdBuffer = new byte[4];
dev.LastError = Command.SendMmcCommand((SafeFileHandle)dev.FileHandle,
dev._cachedScr != null
? (MmcCommands)SecureDigitalCommands.SendOperatingCondition
: MmcCommands.SendOpCond, false, true,
MmcFlags.ResponseSpiR3 | MmcFlags.ResponseR3 | MmcFlags.CommandBcr,
0, 4, 1, ref sdBuffer, out _, out _, out sense);
if(!sense)
{
dev._cachedScr = new byte[4];
Array.Copy(sdBuffer, 0, dev._cachedScr, 0, 4);
}
}
#region SecureDigital / MultiMediaCard
if(dev._cachedCid != null)
{
dev.ScsiType = PeripheralDeviceTypes.DirectAccess;
dev.IsRemovable = false;
if(dev._cachedScr != null)
{
dev.Type = DeviceType.SecureDigital;
CID decoded = Decoders.DecodeCID(dev._cachedCid);
dev.Manufacturer = VendorString.Prettify(decoded.Manufacturer);
dev.Model = decoded.ProductName;
dev.FirmwareRevision =
$"{(decoded.ProductRevision & 0xF0) >> 4:X2}.{decoded.ProductRevision & 0x0F:X2}";
dev.Serial = $"{decoded.ProductSerialNumber}";
}
else
{
dev.Type = DeviceType.MMC;
Aaru.Decoders.MMC.CID decoded = Aaru.Decoders.MMC.Decoders.DecodeCID(dev._cachedCid);
dev.Manufacturer = Aaru.Decoders.MMC.VendorString.Prettify(decoded.Manufacturer);
dev.Model = decoded.ProductName;
dev.FirmwareRevision =
$"{(decoded.ProductRevision & 0xF0) >> 4:X2}.{decoded.ProductRevision & 0x0F:X2}";
dev.Serial = $"{decoded.ProductSerialNumber}";
}
return dev;
}
#endregion SecureDigital / MultiMediaCard
#region USB
Usb.UsbDevice usbDevice = null;
// I have to search for USB disks, floppies and CD-ROMs as separate device types
foreach(string devGuid in new[]
{
Usb.GUID_DEVINTERFACE_FLOPPY, Usb.GUID_DEVINTERFACE_CDROM, Usb.GUID_DEVINTERFACE_DISK,
Usb.GUID_DEVINTERFACE_TAPE
})
{
usbDevice = Usb.FindDrivePath(devicePath, devGuid);
if(usbDevice != null)
break;
}
if(usbDevice != null)
{
dev.UsbDescriptors = usbDevice.BinaryDescriptors;
dev._usbVendor = (ushort)usbDevice._deviceDescriptor.idVendor;
dev._usbProduct = (ushort)usbDevice._deviceDescriptor.idProduct;
dev.UsbManufacturerString = usbDevice.Manufacturer;
dev.UsbProductString = usbDevice.Product;
dev.UsbSerialString =
usbDevice.SerialNumber; // This is incorrect filled by Windows with SCSI/ATA serial number
}
#endregion USB
#region FireWire
// TODO: Implement
dev.IsFireWire = false;
#endregion FireWire
#region PCMCIA
// TODO: Implement
#endregion PCMCIA
return dev;
}
/// <inheritdoc />
public override void Close()
{
if(FileHandle == null)
return;
(FileHandle as SafeFileHandle)?.Close();
FileHandle = null;
}
}