Refactor, IRDKit can take directories

This commit is contained in:
Deterous
2023-11-30 11:05:22 +13:00
parent 11ed114507
commit 4b0d796bd2
8 changed files with 474 additions and 326 deletions
+5 -3
View File
@@ -9,7 +9,8 @@
<TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks>
<RuntimeIdentifiers>win-x86;win-x64;win-arm64;linux-x64;linux-arm64;osx-x64;osx-arm64</RuntimeIdentifiers> <RuntimeIdentifiers>win-x86;win-x64;win-arm64;linux-x64;linux-arm64;osx-x64;osx-arm64</RuntimeIdentifiers>
<LangVersion>latest</LangVersion> <LangVersion>latest</LangVersion>
<Version>0.1.0</Version> <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<Version>0.2.0</Version>
<!-- Package Properties --> <!-- Package Properties -->
<Authors>Deterous</Authors> <Authors>Deterous</Authors>
@@ -23,14 +24,15 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<None Include="./README.md" Pack="true" PackagePath=""/> <None Include="./README.md" Pack="true" PackagePath="" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\LibIRD\LibIRD.csproj" /> <ProjectReference Include="..\LibIRD\LibIRD.csproj" />
<PackageReference Include="CommandLineParser" Version="2.9.1" />
<PackageReference Include="DiscUtils.Core" Version="0.16.13" /> <PackageReference Include="DiscUtils.Core" Version="0.16.13" />
<PackageReference Include="DiscUtils.Iso9660" Version="0.16.13" /> <PackageReference Include="DiscUtils.Iso9660" Version="0.16.13" />
<PackageReference Include="CommandLineParser" Version="2.9.1" /> <PackageReference Include="SabreTools.RedumpLib" Version="1.3.1" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+230 -111
View File
@@ -2,176 +2,146 @@
using DiscUtils; using DiscUtils;
using DiscUtils.Iso9660; using DiscUtils.Iso9660;
using LibIRD; using LibIRD;
using SabreTools.RedumpLib.Web;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.IO.Hashing; using System.IO.Hashing;
using System.Security.Cryptography;
using System.Text; using System.Text;
namespace IRDKit namespace IRDKit
{ {
internal class Program internal class Program
{ {
// IRD Creation /// <summary>
/// IRD Creation Verb
/// </summary>
[Verb("create", HelpText = "Create an IRD from an ISO")] [Verb("create", HelpText = "Create an IRD from an ISO")]
public class CreateOptions public class CreateOptions
{ {
[Value(0, Required = true, HelpText = "Path to an ISO file, or directory of ISO files")] [Value(0, Required = true, HelpText = "Path to an ISO file, or directory of ISO files")]
public string ISOPath { get; set; } public string ISOPath { get; set; }
[Value(1, HelpText = "Path to the IRD file to be created")] [Value(1, Required = false, HelpText = "Path to the IRD file to be created")]
public string IRDPath { get; set; } public string IRDPath { get; set; }
[Option('r', "recurse", HelpText = "Recurse through all subdirectories and generate IRDs for all ISOs")] [Option('b', "layerbreak", HelpText = "Layerbreak value in bytes (define for BD-Video hybrid discs). Default: 12219392")]
public bool Recurse { get; set; } public long? Layerbreak { get; set; }
[Option('k', "key", HelpText = "Hexadecimal representation of the disc key")] [Option('k', "key", HelpText = "Hexadecimal representation of the disc key")]
public string Key { get; set; } public string Key { get; set; }
[Option("key-file", HelpText = "Path to a redump .key file")]
public string KeyFile { get; set; }
[Option('l', "getkey-log", HelpText = "Path to a .getkey.log file")] [Option('l', "getkey-log", HelpText = "Path to a .getkey.log file")]
public string GetKeyLog { get; set; } public string GetKeyLog { get; set; }
[Option('f', "key-file", HelpText = "Path to a redump .key file")]
public string KeyFile { get; set; }
[Option('r', "recurse", HelpText = "Recurse through all subdirectories and generate IRDs for all ISOs")]
public bool Recurse { get; set; }
} }
// IRD Info /// <summary>
/// IRD or ISO information verb
/// </summary>
[Verb("info", HelpText = "Print information from an IRD or ISO")] [Verb("info", HelpText = "Print information from an IRD or ISO")]
public class InfoOptions public class InfoOptions
{ {
[Value(0, Required = true, HelpText = "Path to the IRD or ISO file to be printed")] [Value(0, Required = true, HelpText = "Path to the IRD or ISO file to be printed")]
public string Path { get; set; } public string InPath { get; set; }
[Value(1, Required = false, HelpText = "Path to the text or json file to be created")]
public string OutPath { get; set; }
[Option('j', "json", HelpText = "Print IRD or ISO information as a JSON object")]
public bool Json { get; set; }
} }
/// <summary>
/// Parse command line arguments
/// </summary>
/// <param name="args">Command line arguments</param>
public static void Main(string[] args) public static void Main(string[] args)
{ {
// Parse command line arguments var result = Parser.Default.ParseArguments<CreateOptions, InfoOptions>(args).WithParsed(Run);
var result = Parser.Default.ParseArguments<CreateOptions, InfoOptions>(args)
.WithParsed(Run)
.WithNotParsed(HandleParseError);
}
private static void HandleParseError(IEnumerable<Error> errs)
{
if (errs.IsVersion())
{
// --version
}
else if (errs.IsHelp())
{
// --help
}
else
{
// Parsing error
Console.WriteLine("Parsing error");
}
return;
} }
/// <summary>
/// Perform
/// </summary>
/// <param name="obj"></param>
/// <exception cref="FileNotFoundException"></exception>
/// <exception cref="InvalidFileSystemException"></exception>
private static void Run(object obj) private static void Run(object obj)
{ {
switch (obj) switch (obj)
{ {
case CreateOptions c: case CreateOptions opt:
Console.OutputEncoding = Encoding.UTF8; Console.OutputEncoding = Encoding.UTF8;
// Create new reproducible redump-style IRD with a given hex key
if (c.Key != null)
{
try
{
// Get disc key from hex string
byte[] discKey = Convert.FromHexString(c.Key);
IRD ird1 = new ReIRD(c.ISOPath, discKey);
ird1.Write(c.IRDPath ?? Path.GetFileNameWithoutExtension(c.ISOPath) + ".ird");
ird1.Print();
}
catch (FileNotFoundException)
{
Console.Error.WriteLine("File not found");
}
break;
}
// Create new reproducible redump-style IRD with a given key file
if (c.KeyFile != null)
{
try
{
// Read key from .key file
byte[] discKey = File.ReadAllBytes(c.KeyFile);
IRD ird1 = new ReIRD(c.ISOPath, discKey);
ird1.Write(c.IRDPath ?? Path.GetFileNameWithoutExtension(c.ISOPath) + ".ird");
ird1.Print();
}
catch (FileNotFoundException)
{
Console.Error.WriteLine("File not found");
}
break;
}
// Create new reproducible redump-style IRD with a given GetKey log
if (c.GetKeyLog != null)
{
try
{
IRD ird2 = new ReIRD(c.ISOPath, c.GetKeyLog);
ird2.Write(c.IRDPath ?? Path.GetFileNameWithoutExtension(c.ISOPath) + ".ird");
ird2.Print();
}
catch (FileNotFoundException)
{
Console.Error.WriteLine("File not found");
}
break;
}
// No key provided, try get key from redump.org
// Validate ISO path // Validate ISO path
ArgumentNullException.ThrowIfNull(c.ISOPath); ArgumentNullException.ThrowIfNull(opt.ISOPath);
// Check file exists // If directory, search for all ISOs in current directory
var iso = new FileInfo(c.ISOPath); if (Directory.Exists(opt.ISOPath))
if (!iso.Exists)
throw new FileNotFoundException(nameof(c.ISOPath));
// Compute CRC32 hash
byte[] crc32;
using (FileStream fs = File.OpenRead(c.ISOPath))
{ {
Crc32 hasher = new(); // If recurse option enabled, search recursively
hasher.Append(fs); IEnumerable<string> isoFiles;
crc32 = hasher.GetCurrentHash(); if (opt.Recurse)
Array.Reverse(crc32); {
Console.WriteLine("Automatic key retrieval not yet implemented, search redump.org for: " + Convert.ToHexString(crc32)); Console.WriteLine($"Recursively searching for ISOs in {opt.ISOPath}");
isoFiles = Directory.EnumerateFiles(opt.ISOPath, "*.iso", SearchOption.AllDirectories);
}
else
{
Console.WriteLine($"Searching for ISOs in {opt.ISOPath}");
isoFiles = Directory.EnumerateFiles(opt.ISOPath, "*.iso", SearchOption.TopDirectoryOnly);
}
// Create an IRD file for all ISO files found
foreach (string file in isoFiles)
ProcessISO(opt, file);
break;
} }
// Create a single IRD from an ISO
if (File.Exists(opt.ISOPath))
{
ProcessISO(opt, opt.ISOPath, opt.IRDPath);
break; break;
}
case InfoOptions info: throw new ArgumentException("Not a valid ISO file or directory");
string filetype = Path.GetExtension(info.Path);
case InfoOptions opt:
string filetype = Path.GetExtension(opt.InPath);
if (String.Compare(filetype, ".iso", StringComparison.OrdinalIgnoreCase) == 0) if (String.Compare(filetype, ".iso", StringComparison.OrdinalIgnoreCase) == 0)
{ {
// Open ISO file for reading // Open ISO file for reading
using FileStream fs = new FileStream(info.Path, FileMode.Open, FileAccess.Read) ?? throw new FileNotFoundException(info.Path); using FileStream fs = new FileStream(opt.InPath, FileMode.Open, FileAccess.Read) ?? throw new FileNotFoundException(opt.InPath);
// Validate ISO file stream // Validate ISO file stream
if (!CDReader.Detect(fs)) if (!CDReader.Detect(fs))
throw new InvalidFileSystemException("Not a valid ISO file"); throw new InvalidFileSystemException("Not a valid ISO file");
// Create new ISO reader // Create new ISO reader
CDReader reader = new(fs, true, true); CDReader reader = new(fs, true, true);
File.WriteAllText(opt.OutPath, "{\n");
// Write PS3_DISC.SFB info
using (DiscUtils.Streams.SparseStream s = reader.OpenFile("PS3_DISC.SFB", FileMode.Open, FileAccess.Read)) using (DiscUtils.Streams.SparseStream s = reader.OpenFile("PS3_DISC.SFB", FileMode.Open, FileAccess.Read))
{ {
try try
{ {
PS3_DiscSFB ps3_DiscSFB = new(s); PS3_DiscSFB ps3_DiscSFB = new(s);
ps3_DiscSFB.Print(); if (opt.Json)
{
File.AppendAllText(opt.OutPath, "\"PS3_DISC.SFB\": ");
ps3_DiscSFB.PrintJson(opt.OutPath);
File.AppendAllText(opt.OutPath, ",");
}
else
ps3_DiscSFB.Print(opt.OutPath);
} }
catch catch
{ {
@@ -179,26 +149,175 @@ namespace IRDKit
} }
} }
// Write PARAM.SFO info
using (DiscUtils.Streams.SparseStream s = reader.OpenFile("PS3_GAME\\PARAM.SFO", FileMode.Open, FileAccess.Read)) using (DiscUtils.Streams.SparseStream s = reader.OpenFile("PS3_GAME\\PARAM.SFO", FileMode.Open, FileAccess.Read))
{ {
try try
{ {
ParamSFO paramSFO = new(s); ParamSFO paramSFO = new(s);
paramSFO.Print(); if (opt.Json)
{
File.AppendAllText(opt.OutPath, "\n\"PARAM.SFO\": ");
paramSFO.PrintJson(opt.OutPath);
}
else
paramSFO.Print(opt.OutPath);
} }
catch catch
{ {
Console.WriteLine("./PARAM.SFO not found"); Console.WriteLine("PS3_GAME\\PARAM.SFO not found");
} }
} }
File.AppendAllText(opt.OutPath, "\n}");
} }
else // Assume it is an IRD file else
{ {
IRD.Read(info.Path).Print(); // Assume it is an IRD file
if (opt.Json)
IRD.Read(opt.InPath).PrintJson(opt.OutPath);
else
IRD.Read(opt.InPath).Print(opt.OutPath);
} }
break; break;
} }
} }
public static void ProcessISO(CreateOptions opt, string isoPath, string irdPath = null)
{
// Check file exists
var iso = new FileInfo(isoPath);
if (!iso.Exists)
{
Console.WriteLine($"{nameof(isoPath)} is not a valid File or Directory");
return;
}
Console.WriteLine($"Reading {isoPath}");
// Create new reproducible redump-style IRD with a given hex key
if (opt.Key != null)
{
try
{
// Get disc key from hex string
byte[] discKey = Convert.FromHexString(opt.Key);
Console.WriteLine($"Creating reproducible, redump-style IRD with Key: {opt.Key}");
IRD ird1 = new ReIRD(isoPath, discKey, opt.Layerbreak);
ird1.Write(irdPath ?? Path.GetFileNameWithoutExtension(isoPath) + ".ird");
ird1.Print();
}
catch (FileNotFoundException)
{
Console.Error.WriteLine("File not found");
}
return;
}
// Create new reproducible redump-style IRD with a given key file
if (opt.KeyFile != null)
{
try
{
// Read key from .key file
byte[] discKey = File.ReadAllBytes(opt.KeyFile);
Console.WriteLine($"Creating reproducible, redump-style IRD with Key: {Convert.ToHexString(discKey)}");
IRD ird2 = new ReIRD(isoPath, discKey, opt.Layerbreak);
ird2.Write(irdPath ?? Path.GetFileNameWithoutExtension(isoPath) + ".ird");
ird2.Print();
}
catch (FileNotFoundException)
{
Console.Error.WriteLine("File not found");
}
return;
}
// Create new reproducible redump-style IRD with a given GetKey log
if (opt.GetKeyLog != null)
{
try
{
Console.WriteLine($"Creating reproducible, redump-style IRD with key from: {opt.GetKeyLog}");
IRD ird3 = new ReIRD(isoPath, opt.GetKeyLog);
ird3.Write(irdPath ?? Path.GetFileNameWithoutExtension(isoPath) + ".ird");
ird3.Print();
}
catch (FileNotFoundException)
{
Console.Error.WriteLine("File not found");
}
return;
}
// No key provided, try get key from redump.org
Console.WriteLine("No key provided... Searching for key on redump.org...");
// Compute CRC32 hash
byte[] crc32;
using (FileStream fs = File.OpenRead(isoPath))
{
Crc32 hasher = new();
hasher.Append(fs);
crc32 = hasher.GetCurrentHash();
// Change endianness
Array.Reverse(crc32);
}
string crc32_hash = Convert.ToHexString(crc32).ToLower();
// Search for ISO on redump.org
RedumpHttpClient redump = new();
List<int> ids = redump.CheckSingleSitePage("http://redump.org/discs/system/ps3/quicksearch/" + crc32_hash).ConfigureAwait(false).GetAwaiter().GetResult();
int id;
if (ids.Count == 0)
{
Console.WriteLine("ISO not found in redump, cannot automatically retreive key.");
return;
}
else if (ids.Count > 1)
{
// Compute SHA1 hash
byte[] sha1;
using (FileStream fs = File.OpenRead(isoPath))
{
SHA1 hasher = SHA1.Create();
sha1 = hasher.ComputeHash(fs);
}
string sha1_hash = Convert.ToHexString(sha1).ToLower();
// Search redump.org for SHA1 hash
List<int> ids2 = redump.CheckSingleSitePage("http://redump.org/discs/system/ps3/quicksearch/" + sha1_hash).ConfigureAwait(false).GetAwaiter().GetResult();
if (ids2.Count == 0)
{
Console.WriteLine("ISO not found in redump, cannot automatically retreive key.");
return;
}
else if (ids2.Count > 1)
{
Console.WriteLine("Cannot automatically get key from redump. Please search redump.org and run again with -k");
return;
}
id = ids2[0];
}
else
{
id = ids[0];
}
// Download key file from redump.org
byte[] key = redump.GetByteArrayAsync($"http://redump.org/disc/{id}/key").ConfigureAwait(false).GetAwaiter().GetResult();
if (key.Length != 16)
{
Console.WriteLine("Invalid key obtained from redump");
}
// Create IRD with key from redump
Console.WriteLine($"Creating reproducible, redump-style IRD with Key: {Convert.ToHexString(key)}");
IRD ird = new ReIRD(isoPath, key, opt.Layerbreak);
ird.Write(irdPath ?? Path.GetFileNameWithoutExtension(isoPath) + ".ird");
ird.Print();
}
} }
} }
+81 -25
View File
@@ -6,6 +6,7 @@ using System.IO.Compression;
using System.IO.Hashing; using System.IO.Hashing;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using System.Text.Json;
namespace LibIRD namespace LibIRD
{ {
@@ -663,11 +664,11 @@ namespace LibIRD
// Parse PARAM.SFO file // Parse PARAM.SFO file
ParamSFO paramSFO = new(s); ParamSFO paramSFO = new(s);
// If PS3_DISC.SFB did not set TitleID, use PARAM.SFO TITLE_ID // If PS3_DISC.SFB did not set TitleID, use PARAM.SFO TITLE_ID
TitleID ??= paramSFO["TITLE_ID"]; TitleID ??= paramSFO.Field["TITLE_ID"];
Title = paramSFO["TITLE"]; Title = paramSFO.Field["TITLE"];
// If PS3_DISC.SFB did not set DiscVersion, use PARAM.SFO VERSION // If PS3_DISC.SFB did not set DiscVersion, use PARAM.SFO VERSION
DiscVersion ??= paramSFO["VERSION"]; DiscVersion ??= paramSFO.Field["VERSION"];
AppVersion = paramSFO["APP_VER"]; AppVersion = paramSFO.Field["APP_VER"];
} }
// Determine system update version // Determine system update version
@@ -1266,38 +1267,93 @@ namespace LibIRD
/// <summary> /// <summary>
/// Prints IRD fields to console /// Prints IRD fields to console
/// </summary> /// </summary>
public void Print() /// <param name="printPath">Optional path to save file to</param>
public void Print(string printPath = null)
{ {
// Build string from parameters // Build string from parameters
StringBuilder print = new(); StringBuilder printText = new();
print.AppendLine("IRD Contents:"); printText.AppendLine("IRD Contents:");
print.AppendLine("============="); printText.AppendLine("=============");
// Append IRD fields to string builder // Append IRD fields to string builder
print.AppendLine($"Magic: {Encoding.ASCII.GetString(Magic)}"); printText.AppendLine($"Magic: {Encoding.ASCII.GetString(Magic)}");
print.AppendLine($"IRD Version: {Version}"); printText.AppendLine($"IRD Version: {Version}");
print.AppendLine($"Title ID: {TitleID}"); printText.AppendLine($"Title ID: {TitleID}");
print.AppendLine($"Title: {Title}"); printText.AppendLine($"Title: {Title}");
print.AppendLine($"PUP Version: {SystemVersion}"); printText.AppendLine($"PUP Version: {SystemVersion}");
print.AppendLine($"Disc Version: {DiscVersion}"); printText.AppendLine($"Disc Version: {DiscVersion}");
print.AppendLine($"App Version: {AppVersion}"); printText.AppendLine($"App Version: {AppVersion}");
print.AppendLine($"Regions: {RegionCount}"); printText.AppendLine($"Regions: {RegionCount}");
print.AppendLine($"Files: {FileCount}"); printText.AppendLine($"Files: {FileCount}");
if (ExtraConfig != 0x0000) if (ExtraConfig != 0x0000)
print.AppendLine($"Extra Config: {ExtraConfig:X4}"); printText.AppendLine($"Extra Config: {ExtraConfig:X4}");
if (Attachments != 0x0000) if (Attachments != 0x0000)
print.AppendLine($"Attachments: {Attachments:X4}"); printText.AppendLine($"Attachments: {Attachments:X4}");
print.AppendLine($"Unique ID: {UID:X8}"); printText.AppendLine($"Unique ID: {UID:X8}");
print.AppendLine($"Data 1 Key: {Convert.ToHexString(Data1Key)}"); printText.AppendLine($"Data 1 Key: {Convert.ToHexString(Data1Key)}");
print.AppendLine($"Data 2 Key: {Convert.ToHexString(Data2Key)}"); printText.AppendLine($"Data 2 Key: {Convert.ToHexString(Data2Key)}");
print.AppendLine($"PIC: {Convert.ToHexString(PIC)}"); printText.AppendLine($"PIC: {Convert.ToHexString(PIC)}");
print.AppendLine(); printText.AppendLine();
if (printPath == null)
{
// Ensure UTF-8 will display properly // Ensure UTF-8 will display properly
Console.OutputEncoding = Encoding.UTF8; Console.OutputEncoding = Encoding.UTF8;
// Print formatted string // Print formatted string
Console.Write(print); Console.Write(printText);
}
else
{
File.WriteAllText(printPath, printText.ToString());
}
}
/// <summary>
/// Prints IRD fields to a json object
/// </summary>
/// <param name="jsonPath">Optionally print to json file</param>
public void PrintJson(string jsonPath = null)
{
// Build string from parameters
StringBuilder json = new();
// Append IRD fields to string builder
json.AppendLine("{");
json.AppendLine($" \"Magic\": \"{Encoding.ASCII.GetString(Magic)}\",");
json.AppendLine($" \"IRD Version\": \"{Version}\",");
json.AppendLine($" \"Title ID\": \"{TitleID}\",");
json.AppendLine($" \"Title\": \"{Title}\",");
json.AppendLine($" \"PUP Version\": \"{SystemVersion}\",");
json.AppendLine($" \"Disc Version\": \"{DiscVersion}\",");
json.AppendLine($" \"App Version\": \"{AppVersion}\",");
json.AppendLine($" \"Regions\": \"{RegionCount}\",");
json.AppendLine($" \"Files\": \"{FileCount}\",");
if (ExtraConfig != 0x0000)
json.AppendLine($" \"Extra Config\": \"{ExtraConfig:X4}\",");
if (Attachments != 0x0000)
json.AppendLine($" \"Attachments\": \"{Attachments:X4}\",");
json.AppendLine($" \"Unique ID\": \"{UID:X8}");
json.AppendLine($" \"Data 1 Key\": \"{Convert.ToHexString(Data1Key)}\",");
json.AppendLine($" \"Data 2 Key\": \"{Convert.ToHexString(Data2Key)}\",");
json.AppendLine($" \"PIC\": \"{Convert.ToHexString(PIC)}\"");
json.AppendLine("}");
// If no path given, output to console
if (jsonPath == null)
{
// Ensure UTF-8 will display properly in console
Console.OutputEncoding = Encoding.UTF8;
// Print formatted string to console
Console.Write(json);
}
else
{
// Write to path
File.AppendAllText(jsonPath, json.ToString());
}
} }
#endregion #endregion
+3 -2
View File
@@ -5,14 +5,15 @@
<TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks> <TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks>
<RuntimeIdentifiers>win-x86;win-x64;win-arm64;linux-x64;linux-arm64;osx-x64;osx-arm64</RuntimeIdentifiers> <RuntimeIdentifiers>win-x86;win-x64;win-arm64;linux-x64;linux-arm64;osx-x64;osx-arm64</RuntimeIdentifiers>
<LangVersion>latest</LangVersion> <LangVersion>latest</LangVersion>
<Version>0.1.0</Version> <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<Version>0.2.0</Version>
<!-- Package Properties --> <!-- Package Properties -->
<Authors>Deterous</Authors> <Authors>Deterous</Authors>
<Description>Library for ISO Rebuild Data</Description> <Description>Library for ISO Rebuild Data</Description>
<Copyright>Copyright (c) Deterous 2023</Copyright> <Copyright>Copyright (c) Deterous 2023</Copyright>
<PackageReadmeFile>README.md</PackageReadmeFile> <PackageReadmeFile>README.md</PackageReadmeFile>
<RepositoryUrl>https://github.com/Deterous/LibIRD</RepositoryUrl> <RepositoryUrl>https://github.com/Deterous/LibIRD/</RepositoryUrl>
<RepositoryType>git</RepositoryType> <RepositoryType>git</RepositoryType>
<PackageTags>ps3 iso ird redump</PackageTags> <PackageTags>ps3 iso ird redump</PackageTags>
<PackageLicenseExpression>GPL-3.0-only</PackageLicenseExpression> <PackageLicenseExpression>GPL-3.0-only</PackageLicenseExpression>
+48 -16
View File
@@ -2,6 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Text; using System.Text;
using System.Text.Json;
namespace LibIRD namespace LibIRD
{ {
@@ -25,6 +26,7 @@ namespace LibIRD
/// <summary> /// <summary>
/// A field within the PS3_DISC.SFB file /// A field within the PS3_DISC.SFB file
/// </summary> /// </summary>
/// <remarks>string Key, string Value</remarks>
public Dictionary<string, string> Field { get; private set; } public Dictionary<string, string> Field { get; private set; }
/// <summary> /// <summary>
@@ -35,8 +37,7 @@ namespace LibIRD
public PS3_DiscSFB(string sfbPath) public PS3_DiscSFB(string sfbPath)
{ {
// Validate file path // Validate file path
if (sfbPath == null || sfbPath.Length <= 0) ArgumentNullException.ThrowIfNull(sfbPath, nameof(sfbPath));
throw new ArgumentNullException(nameof(sfbPath));
// Read file as a stream, and parse file // Read file as a stream, and parse file
using FileStream fs = new(sfbPath, FileMode.Open, FileAccess.Read); using FileStream fs = new(sfbPath, FileMode.Open, FileAccess.Read);
@@ -47,7 +48,6 @@ namespace LibIRD
/// Parse PS3_DISC.SFB from stream /// Parse PS3_DISC.SFB from stream
/// </summary> /// </summary>
/// <param name="sfbStream">SFB file stream</param> /// <param name="sfbStream">SFB file stream</param>
/// <exception cref="FileLoadException"></exception>
public PS3_DiscSFB(Stream sfbStream) public PS3_DiscSFB(Stream sfbStream)
{ {
// Parse file stream // Parse file stream
@@ -102,27 +102,59 @@ namespace LibIRD
/// <summary> /// <summary>
/// Prints formatted parameters extracted from PS3_DISC.SFB to console /// Prints formatted parameters extracted from PS3_DISC.SFB to console
/// </summary> /// </summary>
public void Print() /// <param name="printPath">Optionally print to text file</param>
public void Print(string printPath = null)
{ {
// Build string from parameters // Build string from parameters
StringBuilder print = new(); StringBuilder printText = new();
print.AppendLine("PS3_DISC.SFB Contents:"); printText.AppendLine("PS3_DISC.SFB Contents:");
print.AppendLine("======================"); printText.AppendLine("======================");
// Loop through all parameters in PARAM.SFO // Loop through all parameters in PARAM.SFO
foreach (KeyValuePair<string, string> field in Field) foreach (KeyValuePair<string, string> field in Field)
{ printText.AppendLine(field.Key + ": " + field.Value);
print.Append(field.Key); // Blank line
print.Append(": "); printText.Append(Environment.NewLine);
print.AppendLine(field.Value);
}
print.Append(Environment.NewLine);
// Ensure UTF-8 will display properly // If no path given, print to console
if (printPath == null)
{
// Ensure UTF-8 will display properly in console
Console.OutputEncoding = Encoding.UTF8; Console.OutputEncoding = Encoding.UTF8;
// Print formatted string // Print formatted string to console
Console.Write(print); Console.Write(printText);
}
else
{
// Write data to file
File.AppendAllText(printPath, printText.ToString());
}
}
/// <summary>
/// Prints parameters extracted from PS3_DISC.SFB to a json object
/// </summary>
/// <param name="jsonPath">Optionally print to json file</param>
public void PrintJson(string jsonPath = null)
{
// Serialise PS3_Disc.SFB data to a JSON object
string json = JsonSerializer.Serialize(Field, new JsonSerializerOptions { WriteIndented = true });
// If no path given, output to console
if (jsonPath == null)
{
// Ensure UTF-8 will display properly in console
Console.OutputEncoding = Encoding.UTF8;
// Print formatted string to console
Console.Write(json);
}
else
{
// Write to path
File.AppendAllText(jsonPath, json);
}
} }
} }
} }
+83 -143
View File
@@ -1,6 +1,8 @@
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Text; using System.Text;
using System.Text.Json;
namespace LibIRD namespace LibIRD
{ {
@@ -22,91 +24,10 @@ namespace LibIRD
public uint Version { get; private set; } public uint Version { get; private set; }
/// <summary> /// <summary>
/// The location of the first byte of the Key Table /// A field within the PS3_DISC.SFB file
/// </summary> /// </summary>
public uint KeyTableStart { get; private set; } /// <remarks>string Key, string Value</remarks>
public Dictionary<string, string> Field { get; private set; }
/// <summary>
/// The location of the first byte of the Data Table
/// </summary>
public uint DataTableStart { get; private set; }
/// <summary>
/// The number of parameters in the table
/// </summary>
public uint ParamCount { get; private set; }
/// <summary>
/// Parameter, a single entry in parameter table
/// </summary>
public class Param
{
/// <summary>
/// Offset of key, relative to KeyTableStart
/// </summary>
public ushort KeyOffset { get; internal set; }
/// <summary>
/// Format of parameter
/// </summary>
/// <remarks>0x0400 is string, 0x0404 is uint</remarks>
public ushort DataFormat { get; internal set; }
/// <summary>
/// Number of bytes used for parameter
/// </summary>
public uint DataLength { get; internal set; }
/// <summary>
/// Total number of bytes for parameter
/// </summary>
/// <remarks>DataTotal - DataLength is padding of 0x00</remarks>
public uint DataTotal { get; internal set; }
/// <summary>
/// offset of parameter, relative to DataTableStart
/// </summary>
public uint DataOffset { get; internal set; }
/// <summary>
/// The name of the parameter
/// </summary>
public string Name { get; internal set; }
/// <summary>
/// The value of the parameter, if it is a string
/// </summary>
public string StringValue { get; internal set; } = null;
/// <summary>
/// The value of the parameter, if it is a UInt32
/// </summary>
public int IntValue { get; internal set; } = 0;
}
/// <summary>
/// The parameters in the table
/// </summary>
/// <remarks><see cref="ParamCount"/> Params in the table</remarks>
public Param[] Params { get; private set; }
/// <summary>
/// String index overloading, gets string value of given key
/// </summary>
/// <param name="key">Parameter to be retreived</param>
/// <returns>The string value of the given key</returns>
public string this[string key]
{
get
{
int index = Array.FindIndex(Params, param => param.Name == key);
if (index == -1)
return null;
if (Params[index].DataFormat == 0x0404)
return Params[index].IntValue.ToString();
return Params[index].StringValue;
}
}
/// <summary> /// <summary>
/// Constructor using a PARAM.SFO file stream /// Constructor using a PARAM.SFO file stream
@@ -151,95 +72,114 @@ namespace LibIRD
// Parse header // Parse header
Version = br.ReadUInt32(); Version = br.ReadUInt32();
KeyTableStart = br.ReadUInt32(); uint keyTableStart = br.ReadUInt32();
DataTableStart = br.ReadUInt32(); uint dataTableStart = br.ReadUInt32();
ParamCount = br.ReadUInt32(); uint paramCount = br.ReadUInt32();
// Parse parameter metadata // Parse parameter metadata
Params = new Param[ParamCount]; ushort[] keyOffset = new ushort[paramCount];
for (int i = 0; i < ParamCount; i++) uint[] dataFormat = new uint[paramCount];
uint[] dataLength = new uint[paramCount];
uint[] dataTotal = new uint[paramCount];
uint[] dataOffset = new uint[paramCount];
for (int i = 0; i < paramCount; i++)
{ {
Params[i] = new Param keyOffset[i] = br.ReadUInt16();
{ dataFormat[i] = br.ReadUInt16();
KeyOffset = br.ReadUInt16(), dataLength[i] = br.ReadUInt32();
DataFormat = br.ReadUInt16(), dataTotal[i] = br.ReadUInt32();
DataLength = br.ReadUInt32(), dataOffset[i] = br.ReadUInt32();
DataTotal = br.ReadUInt32(),
DataOffset = br.ReadUInt32()
};
} }
// Parse parameters // Parse parameters
for (int i = 0; i < ParamCount; i++) Field = [];
for (int i = 0; i < paramCount; i++)
{ {
// Move stream to ith key // Move stream to ith key
sfoStream.Position = KeyTableStart + Params[i].KeyOffset; sfoStream.Position = keyTableStart + keyOffset[i];
// Determine ith key length // Determine ith key length
uint keyLen = ((i == ParamCount - 1) ? DataTableStart - KeyTableStart : Params[i + 1].KeyOffset) uint keyLen = ((i == paramCount - 1) ? dataTableStart - keyTableStart : keyOffset[i + 1])
- Params[i].KeyOffset; - keyOffset[i];
// Read ith key name // Read ith key name
Params[i].Name = Encoding.ASCII.GetString(br.ReadBytes((int) keyLen)).TrimEnd('\0'); string key = Encoding.ASCII.GetString(br.ReadBytes((int) keyLen)).TrimEnd('\0');
// Move stream to ith data // Move stream to ith data
sfoStream.Position = DataTableStart + Params[i].DataOffset; sfoStream.Position = dataTableStart + dataOffset[i];
// Read ith data, based on data format // Read ith data, based on data format
switch (Params[i].DataFormat) Field[key] = dataFormat[i] switch
{ {
case 0x0400: // Non-null-terminated UTF-8 String // Non-null-terminated UTF-8 String
Params[i].StringValue = Encoding.UTF8.GetString(br.ReadBytes((int)Params[i].DataLength)); 0x0004 => Encoding.UTF8.GetString(br.ReadBytes((int) dataLength[i])),
break; // Null-terminated UTF-8 String
case 0x0402: // Null-terminated UTF-8 String 0x0204 => Encoding.UTF8.GetString(br.ReadBytes((int) dataLength[i])).TrimEnd('\0'),
Params[i].StringValue = Encoding.UTF8.GetString(br.ReadBytes((int)Params[i].DataLength)).TrimEnd('\0'); // Integer
break; 0x0404 => br.ReadInt32().ToString(),
case 0x0404: // Integer // Unknown data format, assume null-terminated string
//if (Params[i].DataLength != 4) _ => Encoding.UTF8.GetString(br.ReadBytes((int) dataLength[i])).TrimEnd('\0'),
//throw new ArgumentException("Integer parameter not 4 bytes?"); };
Params[i].IntValue = br.ReadInt32();
break;
default: // Unknown data format, assume null-terminated string
Params[i].StringValue = Encoding.UTF8.GetString(br.ReadBytes((int)Params[i].DataLength)).TrimEnd('\0');
break;
}
} }
} }
/// <summary> /// <summary>
/// Prints formatted parameters extracted from PARAM.SFO to console /// Prints formatted parameters extracted from PARAM.SFO to console
/// </summary> /// </summary>
public void Print() /// <param name="printPath">Optionally print to text file</param>
public void Print(string printPath = null)
{ {
// Build string from parameters // Build string from parameters
StringBuilder print = new(); StringBuilder printText = new();
print.AppendLine("PARAM.SFO Contents:"); printText.AppendLine("PARAM.SFO Contents:");
print.AppendLine("===================="); printText.AppendLine("====================");
// Loop through all parameters in PARAM.SFO // Loop through all parameters in PARAM.SFO
for (int i = 0; i < ParamCount; i++) foreach (KeyValuePair<string, string> field in Field)
{ printText.AppendLine(field.Key + ": " + field.Value);
print.Append(Params[i].Name); // Blank line
print.Append(' '); printText.Append(Environment.NewLine);
for (int j = Params[i].Name.Length; j < 20; j++)
print.Append(' ');
switch (Params[i].DataFormat)
{
case 0x0404:
print.Append(Params[i].IntValue +Environment.NewLine);
break;
default:
print.AppendLine(Params[i].StringValue);
break;
}
}
print.Append(Environment.NewLine);
// Ensure UTF-8 will display properly // If no path given, print to console
if (printPath == null)
{
// Ensure UTF-8 will display properly in console
Console.OutputEncoding = Encoding.UTF8; Console.OutputEncoding = Encoding.UTF8;
// Print formatted string // Print formatted string to console
Console.Write(print); Console.Write(printText);
}
else
{
// Write data to file
File.AppendAllText(printPath, printText.ToString());
}
}
/// <summary>
/// Prints parameters extracted from PARAM.SFO to a json object
/// </summary>
/// <param name="jsonPath">Optionally print to json file</param>
public void PrintJson(string jsonPath = null)
{
// Serialise PS3_Disc.SFB data to a JSON object
string json = JsonSerializer.Serialize(Field, new JsonSerializerOptions { WriteIndented = true });
// If no path given, output to console
if (jsonPath == null)
{
// Ensure UTF-8 will display properly in console
Console.OutputEncoding = Encoding.UTF8;
// Print formatted string to console
Console.Write(json);
}
else
{
// Write to path
File.AppendAllText(jsonPath, json);
}
} }
} }
} }
+12 -18
View File
@@ -67,10 +67,9 @@ namespace LibIRD
/// </summary> /// </summary>
/// <param name="isoPath">Path to the ISO</param> /// <param name="isoPath">Path to the ISO</param>
/// <param name="getKeyLog">Path to the GetKey log file</param> /// <param name="getKeyLog">Path to the GetKey log file</param>
/// <exception cref="ArgumentNullException"></exception> /// <param name="layerbreak">Layerbreak value, in sectors</param>
/// <exception cref="FileNotFoundException"></exception>
/// <exception cref="InvalidDataException"></exception> /// <exception cref="InvalidDataException"></exception>
public ReIRD(string isoPath, string getKeyLog) : base(isoPath, getKeyLog, true) public ReIRD(string isoPath, string getKeyLog, long? layerbreak = null) : base(isoPath, getKeyLog, true)
{ {
// Generate Unique Identifier using ISO CRC32 // Generate Unique Identifier using ISO CRC32
UID = GenerateUID(isoPath); UID = GenerateUID(isoPath);
@@ -80,12 +79,10 @@ namespace LibIRD
// Generate Data 2 using Disc ID // Generate Data 2 using Disc ID
DiscID = GenerateID(Size); DiscID = GenerateID(Size);
// Check that GetKey log matches expected Disc ID
//if (!((ReadOnlySpan<byte>)Data2Key).SequenceEqual(d2))
// throw new InvalidDataException("Unexpected Disc ID in .getkey.log");
// Generate Disc PIC // Generate Disc PIC
byte[] pic = GeneratePIC(Size); byte[] pic = GeneratePIC(Size, layerbreak * SectorSize);
// Check that GetKey log matches expected PIC // Check that GetKey log matches expected PIC
if (!((ReadOnlySpan<byte>)PIC).SequenceEqual(pic)) if (!((ReadOnlySpan<byte>)PIC).SequenceEqual(pic))
throw new InvalidDataException("Unexpected PIC in .getkey.log"); throw new InvalidDataException("Unexpected PIC in .getkey.log");
@@ -96,10 +93,9 @@ namespace LibIRD
/// </summary> /// </summary>
/// <param name="isoPath">Path to the ISO</param> /// <param name="isoPath">Path to the ISO</param>
/// <param name="key">Disc Key, redump-style (AES encrypted Data 1)</param> /// <param name="key">Disc Key, redump-style (AES encrypted Data 1)</param>
/// <param name="layerbreak">Layerbreak value, in sectors</param>
/// <param name="region">Disc Region</param> /// <param name="region">Disc Region</param>
/// <exception cref="ArgumentNullException"></exception> public ReIRD(string isoPath, byte[] key, long? layerbreak = null, Region region = Region.NONE)
/// <exception cref="FileNotFoundException"></exception>
public ReIRD(string isoPath, byte[] key, Region region = Region.NONE)
{ {
// Generate Unique Identifier using ISO CRC32 // Generate Unique Identifier using ISO CRC32
UID = GenerateUID(isoPath); UID = GenerateUID(isoPath);
@@ -114,7 +110,7 @@ namespace LibIRD
DiscID = GenerateID(Size, region); DiscID = GenerateID(Size, region);
// Generate Disc PIC // Generate Disc PIC
PIC = GeneratePIC(Size); PIC = GeneratePIC(Size, layerbreak * SectorSize);
// Generate IRD fields // Generate IRD fields
GenerateIRD(isoPath, true); GenerateIRD(isoPath, true);
@@ -144,7 +140,7 @@ namespace LibIRD
/// Generates the PIC data for a given ISO size in bytes /// Generates the PIC data for a given ISO size in bytes
/// </summary> /// </summary>
/// <param name="size">Total ISO size in number of bytes</param> /// <param name="size">Total ISO size in number of bytes</param>
/// <param name="layer_break">Layer break value, byte at which disc layers are split across</param> /// <param name="layerbreak">Layer break value, byte at which disc layers are split across</param>
/// <param name="exactIRD">True to generate a PIC in 3k3y style (0x03 at 115th byte for BD-50 discs)</param> /// <param name="exactIRD">True to generate a PIC in 3k3y style (0x03 at 115th byte for BD-50 discs)</param>
/// <exception cref="ArgumentException"></exception> /// <exception cref="ArgumentException"></exception>
private static byte[] GeneratePIC(long size, long? layerbreak = null, bool exactIRD = false) private static byte[] GeneratePIC(long size, long? layerbreak = null, bool exactIRD = false)
@@ -171,7 +167,7 @@ namespace LibIRD
long l0_start_sector = 1048576; long l0_start_sector = 1048576;
// Layer 0 end sector = start sector + layerbreak - 2 // Layer 0 end sector = start sector + layerbreak - 2
long l0_end_sector = layer_break + l0_start_sector - 2; long l0_end_sector = (layer_break / SectorSize) + l0_start_sector - 2;
// Convert end sector location to hex values for PIC // Convert end sector location to hex values for PIC
byte[] l0es = [(byte)((l0_end_sector >> 24) & 0xFF), byte[] l0es = [(byte)((l0_end_sector >> 24) & 0xFF),
(byte)((l0_end_sector >> 16) & 0xFF), (byte)((l0_end_sector >> 16) & 0xFF),
@@ -179,7 +175,7 @@ namespace LibIRD
(byte)((l0_end_sector >> 0) & 0xFF)]; (byte)((l0_end_sector >> 0) & 0xFF)];
// Layer 1 start sector = end of disc (0x01EFFFFE) - layerbreak + 2 // Layer 1 start sector = end of disc (0x01EFFFFE) - layerbreak + 2
long l1_start_sector = 32505854 - layer_break + 2; long l1_start_sector = 32505854 - (layer_break / SectorSize) + 2;
// Convert start of start sector location to hex values for PIC // Convert start of start sector location to hex values for PIC
byte[] l1ss = [(byte)((l1_start_sector >> 24) & 0xFF), byte[] l1ss = [(byte)((l1_start_sector >> 24) & 0xFF),
(byte)((l1_start_sector >> 16) & 0xFF), (byte)((l1_start_sector >> 16) & 0xFF),
@@ -262,8 +258,7 @@ namespace LibIRD
private static uint GenerateUID(string isoPath) private static uint GenerateUID(string isoPath)
{ {
// Validate ISO path // Validate ISO path
if (isoPath == null || isoPath.Length <= 0) ArgumentNullException.ThrowIfNull(isoPath, nameof(isoPath));
throw new ArgumentNullException(nameof(isoPath));
// Check file exists // Check file exists
var iso = new FileInfo(isoPath); var iso = new FileInfo(isoPath);
@@ -292,8 +287,7 @@ namespace LibIRD
private static long CalculateSize(string isoPath) private static long CalculateSize(string isoPath)
{ {
// Validate ISO path // Validate ISO path
if (isoPath == null || isoPath.Length <= 0) ArgumentNullException.ThrowIfNull(isoPath, nameof(isoPath));
throw new ArgumentNullException(nameof(isoPath));
// Check file exists // Check file exists
var iso = new FileInfo(isoPath); var iso = new FileInfo(isoPath);
+4
View File
@@ -17,3 +17,7 @@ For detailed usage, read more [here](IRDKit).
## Using the LibIRD library ## Using the LibIRD library
LibIRD was originally made for creating reproducible, redump-style IRDs when dumping PS3 discs with [MPF](https://github.com/SabreTools/MPF). If you wish to integrate LibIRD into your own application, read the examples [here](LibIRD). LibIRD was originally made for creating reproducible, redump-style IRDs when dumping PS3 discs with [MPF](https://github.com/SabreTools/MPF). If you wish to integrate LibIRD into your own application, read the examples [here](LibIRD).
## Limitations
Currently, LibIRD does not produce correct IRDs for ISOs with non-contiguous files. Therefore, do not consider this library "stable" until v1.0.0 is released.