15 Commits
11 changed files with 535 additions and 298 deletions
+8 -9
View File
@@ -3,19 +3,18 @@
<PropertyGroup>
<!-- Assembly Properties -->
<OutputType>Exe</OutputType>
<PackAsTool>true</PackAsTool>
<ToolCommandName>irdkit</ToolCommandName>
<PackageOutputPath>./nupkg</PackageOutputPath>
<TargetName>irdkit</TargetName>
<AssemblyName>irdkit</AssemblyName>
<TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks>
<RuntimeIdentifiers>win-x86;win-x64;win-arm64;linux-x64;linux-arm64;osx-x64;osx-arm64</RuntimeIdentifiers>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<Version>0.3.0</Version>
<Version>0.5.0</Version>
<!-- Package Properties -->
<Authors>Deterous</Authors>
<Description>Library for ISO Rebuild Data</Description>
<Copyright>Copyright (c) Deterous 2023</Copyright>
<Copyright>Copyright (c) Deterous 2023-2024</Copyright>
<PackageReadmeFile>README.md</PackageReadmeFile>
<RepositoryUrl>https://github.com/Deterous/LibIRD</RepositoryUrl>
<RepositoryType>git</RepositoryType>
@@ -28,11 +27,11 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\LibIRD\LibIRD.csproj" />
<ProjectReference Include="..\DiscUtils\Library\DiscUtils.Core\DiscUtils.Core.csproj" />
<ProjectReference Include="..\DiscUtils\Library\DiscUtils.Iso9660\DiscUtils.Iso9660.csproj" />
<ProjectReference Include="..\LibIRD\LibIRD.csproj" PrivateAssets="All" />
<ProjectReference Include="..\DiscUtils\Library\DiscUtils.Core\DiscUtils.Core.csproj" PrivateAssets="All" />
<ProjectReference Include="..\DiscUtils\Library\DiscUtils.Iso9660\DiscUtils.Iso9660.csproj" PrivateAssets="All" />
<PackageReference Include="CommandLineParser" Version="2.9.1" />
<PackageReference Include="SabreTools.RedumpLib" Version="1.3.2" />
<PackageReference Include="SabreTools.RedumpLib" Version="1.3.3" />
</ItemGroup>
</Project>
+250 -110
View File
@@ -31,7 +31,7 @@ namespace IRDKit
public string IRDPath { get; set; }
[Option('b', "layerbreak", HelpText = "Layerbreak value in bytes (use with BD-Video hybrid discs). Default: 12219392")]
public long? Layerbreak { get; set; }
public long? Layerbreak { get; set; }
[Option('k', "key", HelpText = "Hexadecimal representation of the disc key")]
public string Key { get; set; }
@@ -44,6 +44,9 @@ namespace IRDKit
[Option('r', "recurse", HelpText = "Recurse through all subdirectories and generate IRDs for all ISOs")]
public bool Recurse { get; set; }
[Option('v', "verbose", HelpText = "Print more information during IRD creation")]
public bool Verbose { get; set; }
}
/// <summary>
@@ -65,9 +68,9 @@ namespace IRDKit
public bool Recurse { get; set; }
}
/// <summary>
/// IRD diff command
/// </summary>
/// <summary>
/// IRD diff command
/// </summary>
[Verb("diff", HelpText = "Compare two IRDs and print their differences")]
public class DiffOptions
{
@@ -111,12 +114,17 @@ namespace IRDKit
case CreateOptions opt:
// Validate ISO paths
ArgumentNullException.ThrowIfNull(opt.ISOPath);
if (opt.ISOPath == null || !opt.ISOPath.Any())
{
Console.Error.WriteLine("Provide a valid ISO path to create an IRD");
return;
}
foreach (string isoPath in opt.ISOPath)
{
// Validate ISO path
ArgumentNullException.ThrowIfNull(isoPath);
if (string.IsNullOrEmpty(isoPath))
continue;
// If directory, search for all ISOs in current directory
if (Directory.Exists(isoPath))
@@ -125,47 +133,59 @@ namespace IRDKit
IEnumerable<string> isoFiles;
if (opt.Recurse)
{
if (isoPath == ".")
if (opt.Verbose && isoPath == ".")
Console.WriteLine($"Recursively searching for ISOs in current directory");
else
else if (opt.Verbose)
Console.WriteLine($"Recursively searching for ISOs in {isoPath}");
isoFiles = Directory.EnumerateFiles(isoPath, "*.iso", SearchOption.AllDirectories);
}
else
{
if (isoPath == ".")
if (opt.Verbose && isoPath == ".")
Console.WriteLine($"Searching for ISOs in current directory");
else
else if (opt.Verbose)
Console.WriteLine($"Searching for ISOs in {isoPath}");
isoFiles = Directory.EnumerateFiles(isoPath, "*.iso", SearchOption.TopDirectoryOnly);
}
// Warn if no files are found
if (!isoFiles.Any())
Console.WriteLine("No ISOs found (ensure .iso extension)");
{
if (opt.Recurse)
Console.Error.WriteLine($"No ISOs found in {isoPath} (ensure .iso extension)");
else
Console.Error.WriteLine($"No ISOs found in {isoPath} (ensure .iso extension, or try use -r)");
continue;
}
// Determine output IRD folder
string outputPath = opt.IRDPath;
if (File.Exists(opt.IRDPath))
outputPath = Path.GetDirectoryName(opt.IRDPath);
// Create an IRD file for all ISO files found
foreach (string file in isoFiles)
ISO2IRD(file);
foreach (string file in isoFiles.OrderBy(x => x))
ISO2IRD(file, irdPath: outputPath, keyPath: opt.KeyFile, verbose: opt.Verbose);
}
else
{
// Check that given file exists
if (!File.Exists(isoPath)) throw new ArgumentException("Not a valid file or directory");
if (!File.Exists(isoPath))
{
Console.Error.WriteLine($"ISO not found: {isoPath}");
return;
}
// Save to given output path, if only 1 IRD is being created
if (opt.ISOPath.Count() == 1 && opt.IRDPath != null && opt.IRDPath != "")
{
string irdPath = ISO2IRD(isoPath, opt.IRDPath, opt.Key, opt.KeyFile, opt.GetKeyLog, opt.Layerbreak);
if (irdPath != null)
Console.WriteLine($"IRD saved to {irdPath}");
}
string irdPath;
// Save to given output path and filename, if only 1 IRD is being created
if (opt.ISOPath.Count() == 1)
irdPath = ISO2IRD(isoPath, irdPath: opt.IRDPath, hexKey: opt.Key, keyPath: opt.KeyFile, getKeyLog: opt.GetKeyLog, layerbreak: opt.Layerbreak, verbose: opt.Verbose);
// Save to given output path, if more than 1 IRD is being created
else
{
string irdPath = ISO2IRD(isoPath, null, opt.Key, opt.KeyFile, opt.GetKeyLog, opt.Layerbreak);
if (irdPath != null)
Console.WriteLine($"IRD saved to {irdPath}");
}
irdPath = ISO2IRD(isoPath, irdPath: Path.GetDirectoryName(opt.IRDPath), verbose: opt.Verbose);
if (irdPath != null)
Console.WriteLine($"IRD saved to {irdPath}");
}
}
@@ -175,7 +195,11 @@ namespace IRDKit
case InfoOptions opt:
// Validate required parameter
ArgumentNullException.ThrowIfNull(opt.InPath);
if (opt.InPath == null || !opt.InPath.Any())
{
Console.Error.WriteLine("Provide a valid ISO or IRD path to print info about");
return;
}
// Clear the output file path if it exists
if (opt.OutPath != null && opt.OutPath != "")
@@ -184,7 +208,8 @@ namespace IRDKit
foreach (string filePath in opt.InPath)
{
// Validate path
ArgumentNullException.ThrowIfNull(filePath);
if (string.IsNullOrEmpty(filePath))
continue;
// If directory, search for all ISOs in current directory
if (Directory.Exists(filePath))
@@ -213,7 +238,10 @@ namespace IRDKit
// Warn if no files are found
if (!isoFiles.Any() && !irdFiles.Any())
Console.WriteLine("No IRDs or ISOs found (ensure .ird and .iso extensions)");
{
Console.Error.WriteLine("No IRDs or ISOs found (ensure .ird and .iso extensions)");
return;
}
// Open JSON object
if (opt.Json)
@@ -245,7 +273,7 @@ namespace IRDKit
{
// Not a valid ISO file despite extension, assume file is an IRD
if (!opt.Json)
Console.WriteLine($"{file} is not a valid ISO file\n");
Console.Error.WriteLine($"{file} is not a valid ISO file\n");
}
}
@@ -264,7 +292,11 @@ namespace IRDKit
else
{
// Check that given file exists
if (!File.Exists(filePath)) throw new ArgumentException($"{filePath} is not a valid file or directory");
if (!File.Exists(filePath))
{
Console.Error.WriteLine($"{filePath} is not a valid file");
continue;
}
// Print info from given file
PrintInfo(filePath, opt.Json, true, opt.OutPath);
@@ -279,11 +311,12 @@ namespace IRDKit
// Process options from a `diff` command
case DiffOptions opt:
// Validate required parameter
ArgumentNullException.ThrowIfNull(opt.InPath1);
ArgumentNullException.ThrowIfNull(opt.InPath2);
if (!File.Exists(opt.InPath1)) throw new ArgumentException($"{opt.InPath1} is not a valid file or directory");
if (!File.Exists(opt.InPath2)) throw new ArgumentException($"{opt.InPath2} is not a valid file or directory");
// Validate required parameters
if (opt.InPath1 == null || opt.InPath2 == null || !File.Exists(opt.InPath1) || !File.Exists(opt.InPath2))
{
Console.Error.WriteLine("Provide two paths to IRDs to compare");
return;
}
// Clear the output file path if it exists
if (opt.OutPath != null && opt.OutPath != "")
@@ -355,9 +388,9 @@ namespace IRDKit
if (json)
return;
if (isISO)
Console.WriteLine($"{inPath} is not a valid ISO file\n");
Console.Error.WriteLine($"{inPath} is not a valid ISO file\n");
else
Console.WriteLine($"{inPath} is not a valid IRD file\n");
Console.Error.WriteLine($"{inPath} is not a valid IRD file\n");
}
}
@@ -372,10 +405,13 @@ namespace IRDKit
public static void PrintISO(string isoPath, bool json, bool single = true, string outPath = null)
{
// Open ISO file for reading
using FileStream fs = new FileStream(isoPath, FileMode.Open, FileAccess.Read) ?? throw new FileNotFoundException(isoPath);
using FileStream fs = new(isoPath, FileMode.Open, FileAccess.Read);
// Validate ISO file stream
if (!CDReader.Detect(fs))
throw new InvalidFileSystemException($"{isoPath} is not a valid ISO file");
if (fs == null || !CDReader.Detect(fs))
{
Console.Error.WriteLine($"{isoPath} is not a valid ISO file");
return;
}
// Create new ISO reader
using CDReader reader = new(fs, true, true);
@@ -412,7 +448,7 @@ namespace IRDKit
catch (FileNotFoundException)
{
if (!json)
Console.WriteLine($"{isoPath} is not a valid PS3 ISO file\n");
Console.Error.WriteLine($"{isoPath} is not a valid PS3 ISO file\n");
return;
}
@@ -435,7 +471,7 @@ namespace IRDKit
catch (FileNotFoundException)
{
if (!json)
Console.WriteLine($"\\PS3_GAME\\PARAM.SFO not found in {isoPath}\n");
Console.Error.WriteLine($"\\PS3_GAME\\PARAM.SFO not found in {isoPath}\n");
}
// End JSON object
@@ -469,7 +505,7 @@ namespace IRDKit
// Check they are different IRDs
if (Path.GetFullPath(irdPath1) == Path.GetFullPath(irdPath2))
{
Console.WriteLine("Provide two different IRDs for a diff");
Console.Error.WriteLine("Provide two different IRDs for a diff");
return;
}
@@ -480,45 +516,69 @@ namespace IRDKit
// Build a formatted diff
StringBuilder printText = new();
// Print any version difference
if (IRD1.Version != IRD2.Version)
printText.AppendLine($"Version: {IRD1.Version} vs {IRD2.Version}");
// Print any title ID difference
if (IRD1.TitleID != IRD2.TitleID)
printText.AppendLine($"TitleID: {IRD1.TitleID} vs {IRD2.TitleID}");
// Print any title difference
if (IRD1.Title != IRD2.Title)
printText.AppendLine($"Title: {IRD1.Title} vs {IRD2.Title}");
printText.AppendLine($"Title: \"{IRD1.Title}\" vs \"{IRD2.Title}\"");
// Print any system version difference
if (IRD1.SystemVersion != IRD2.SystemVersion)
printText.AppendLine($"PUP Version: {IRD1.SystemVersion} vs {IRD2.SystemVersion}");
// Print any disc version difference
if (IRD1.DiscVersion != IRD2.DiscVersion)
printText.AppendLine($"Disc Version: {IRD1.DiscVersion} vs {IRD2.DiscVersion}");
// Print any app version difference
if (IRD1.AppVersion != IRD2.AppVersion)
printText.AppendLine($"App Version: {IRD1.AppVersion} vs {IRD2.AppVersion}");
// Un-gzip the headers to compare them
byte[] header1 = Decompress(IRD1.Header);
byte[] header2 = Decompress(IRD2.Header);
// Print the difference in header length, if not 0
if (header1.Length != header2.Length)
printText.AppendLine($"Header Length: {header1.Length} vs {header2.Length}");
if (!header1.SequenceEqual(header2))
printText.AppendLine($"Header: Differs");
// Print number of bytes that the headers differ by, if not 0
int headerDiff;
if (header1.Length < header2.Length)
headerDiff = header2.Length - header1.Length + header1.Where((x, i) => x != header2[i]).Count();
else
headerDiff = header1.Length - header2.Length + header2.Where((x, i) => x != header1[i]).Count();
if (headerDiff != 0)
printText.AppendLine($"Header: Differs by {headerDiff} bytes");
// Un-gzip the footers to compare them
byte[] footer1 = Decompress(IRD1.Footer);
byte[] footer2 = Decompress(IRD2.Footer);
// Print the difference in footer length, if not 0
if (footer1.Length != footer2.Length)
printText.AppendLine($"Footer Length: {footer1.Length} vs {footer2.Length}");
if (!footer1.SequenceEqual(footer2))
printText.AppendLine($"Footer: Differs");
// Print number of bytes that the footers differ by, if not 0
int footerDiff;
if (footer1.Length < footer2.Length)
footerDiff = footer2.Length - footer1.Length + footer1.Where((x, i) => x != footer2[i]).Count();
else
footerDiff = footer1.Length - footer2.Length + footer2.Where((x, i) => x != footer1[i]).Count();
if (footerDiff != 0)
printText.AppendLine($"Footer: Differs by {footerDiff} bytes");
// Print the difference in number of regions, if not 0
if (IRD1.RegionCount != IRD2.RegionCount)
printText.AppendLine($"Region Count: {IRD1.RegionCount} vs {IRD2.RegionCount}");
// Print any differences in region hashes
int regionCount = IRD2.RegionCount < IRD1.RegionCount ? IRD2.RegionCount : IRD1.RegionCount;
if (regionCount > IRD1.RegionHashes.Length)
regionCount = IRD1.RegionHashes.Length;
@@ -530,44 +590,58 @@ namespace IRDKit
printText.AppendLine($"Region {i} Hash: {Convert.ToHexString(IRD1.RegionHashes[i])} vs {Convert.ToHexString(IRD2.RegionHashes[i])}");
}
// Print the difference in number of files, if not 0
if (IRD1.FileCount != IRD2.FileCount)
printText.AppendLine($"File Count: {IRD1.FileCount} vs {IRD2.FileCount}");
int fileCount = IRD2.FileCount < IRD1.FileCount ? (int)IRD2.FileCount : (int)IRD1.FileCount;
if (fileCount > IRD1.FileKeys.Length)
fileCount = IRD1.FileKeys.Length;
if (fileCount > IRD2.FileKeys.Length)
fileCount = IRD2.FileKeys.Length;
if (fileCount > IRD1.FileHashes.Length)
fileCount = IRD1.FileHashes.Length;
if (fileCount > IRD2.FileHashes.Length)
fileCount = IRD2.FileHashes.Length;
for (int i = 0; i < fileCount; i++)
// Print the mismatch file hashes, for each file offset at which they differ
List<long> missingOffsets1 = [];
List<long> missingOffsets2 = [];
for (int i = 0; i < IRD1.FileKeys.Length; i++)
{
if (IRD1.FileKeys[i] != IRD2.FileKeys[i])
printText.AppendLine($"File {i} Offset: {IRD1.FileKeys[i]} vs {IRD2.FileKeys[i]}");
if (!IRD1.FileHashes[i].SequenceEqual(IRD2.FileHashes[i]))
printText.AppendLine($"File {i} Hash: {Convert.ToHexString(IRD1.FileHashes[i])} vs {Convert.ToHexString(IRD2.FileHashes[i])}");
int j = Array.FindIndex(IRD2.FileKeys, element => element == IRD1.FileKeys[i]);
if (j == -1)
missingOffsets2.Add(IRD1.FileKeys[i]);
if (j != -1 && !IRD1.FileHashes[i].SequenceEqual(IRD2.FileHashes[j]))
printText.AppendLine($"File Hash at Offset {IRD1.FileKeys[i]}: {Convert.ToHexString(IRD1.FileHashes[i])} vs {Convert.ToHexString(IRD2.FileHashes[j])}");
}
for (int i = 0; i < IRD2.FileKeys.Length; i++)
{
int j = Array.FindIndex(IRD1.FileKeys, element => element == IRD2.FileKeys[i]);
if (j == -1)
missingOffsets1.Add(IRD2.FileKeys[i]);
}
// Print the file offsets that differ
if (missingOffsets1.Count > 0)
printText.AppendLine($"File Offsets not Present in {irdPath1}: {string.Join(", ", missingOffsets1)}");
if (missingOffsets2.Count > 0)
printText.AppendLine($"File Offsets not Present in {irdPath2}: {string.Join(", ", missingOffsets2)}");
// Print any extra config data difference
if (IRD1.ExtraConfig != IRD2.ExtraConfig)
printText.AppendLine($"Extra Config: {IRD1.ExtraConfig:X4} vs {IRD2.ExtraConfig:X4}");
// Print any attachments data difference
if (IRD1.Attachments != IRD2.Attachments)
printText.AppendLine($"Attachments: {IRD1.Attachments:X4} vs {IRD2.Attachments:X4}");
// Print any unique ID difference
if (IRD1.UID != IRD2.UID)
printText.AppendLine($"Unique ID: {IRD1.UID:X8} vs {IRD2.UID:X8}");
// Print any data 1 key difference
if (!IRD1.Data1Key.SequenceEqual(IRD2.Data1Key))
printText.AppendLine($"Data 1 Key: {Convert.ToHexString(IRD1.Data1Key)} vs {Convert.ToHexString(IRD2.Data1Key)}");
// Print any data 2 key difference
if (!IRD1.Data2Key.SequenceEqual(IRD2.Data2Key))
printText.AppendLine($"Data 2 Key: {Convert.ToHexString(IRD1.Data2Key)} vs {Convert.ToHexString(IRD2.Data2Key)}");
// Print any PIC difference
if (!IRD1.PIC.SequenceEqual(IRD2.PIC))
printText.AppendLine($"PIC: {Convert.ToHexString(IRD1.PIC)} vs {Convert.ToHexString(IRD2.PIC)}");
// Write formatted string to file if output path provided, otherwise to console
if (outPath != null)
File.AppendAllText(outPath, printText.ToString());
else
@@ -583,17 +657,32 @@ namespace IRDKit
/// <param name="keyPath">Disc key file (overridden by hex string if present)</param>
/// <param name="getKeyLog">GetKey log file (overridden by disc key or key file if present)</param>
/// <param name="layerbreak">Layerbreak value of disc</param>
public static string ISO2IRD(string isoPath, string irdPath = null, string hexKey = null, string keyPath = null, string getKeyLog = null, long? layerbreak = null)
public static string ISO2IRD(string isoPath, string irdPath = null, string hexKey = null, string keyPath = null, string getKeyLog = null, long? layerbreak = null, bool verbose = false)
{
// Check file exists
FileInfo iso = new(isoPath);
FileInfo iso;
try
{
iso = new(isoPath);
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message + ", failed to create IRD");
return null;
}
if (!iso.Exists)
{
Console.WriteLine($"{nameof(isoPath)} is not a valid file or directory");
Console.Error.WriteLine($"{nameof(isoPath)} is not a valid file or directory");
return null;
}
// Determine IRD path if only folder given
if (Directory.Exists(irdPath))
irdPath = Path.Combine(irdPath, Path.GetFileName(Path.ChangeExtension(isoPath, ".ird")));
// Determine IRD path if none given
if (irdPath == string.Empty)
irdPath = Path.GetFileName(Path.ChangeExtension(isoPath, ".ird"));
irdPath ??= Path.ChangeExtension(isoPath, ".ird");
// Create new reproducible redump-style IRD with a given hex key
@@ -604,17 +693,21 @@ namespace IRDKit
// Get disc key from hex string
byte[] discKey = Convert.FromHexString(hexKey);
if (discKey == null || discKey.Length != 16)
throw new ArgumentException(hexKey);
Console.WriteLine($"Creating {irdPath} with Key: {hexKey}");
IRD ird1 = new ReIRD(isoPath, discKey, layerbreak);
ird1.Write(irdPath);
ird1.Print();
return irdPath;
Console.Error.WriteLine($"{hexKey} is not a valid key, detecting key automatically...");
else
{
Console.WriteLine($"Creating {irdPath} with Key: {hexKey}");
IRD ird1 = new ReIRD(isoPath, discKey, layerbreak);
ird1.Write(irdPath);
if (verbose)
ird1.Print();
return irdPath;
}
}
catch (ArgumentException)
catch (ArgumentException e)
{
Console.Error.WriteLine($"{hexKey} is not a valid key, detecting key automatically...");
Console.Error.WriteLine(e.Message + ", failed to create IRD");
return null;
}
catch (FileNotFoundException)
{
@@ -626,19 +719,31 @@ namespace IRDKit
// Create new reproducible redump-style IRD with a given key file
if (keyPath != null)
{
// Read key from .key file
byte[] discKey = File.ReadAllBytes(keyPath);
try
{
IRD ird2 = new ReIRD(isoPath, discKey, layerbreak);
Console.WriteLine($"Creating {irdPath} with Key: {Convert.ToHexString(discKey)}");
ird2.Write(irdPath);
ird2.Print();
return irdPath;
// If key directory was given, append filename and .key
if (Directory.Exists(keyPath))
{
keyPath = Path.Combine(keyPath, Path.ChangeExtension(Path.GetFileName(isoPath), ".key"));
}
// Read key from .key file
byte[] discKey = File.ReadAllBytes(keyPath);
if (discKey == null || discKey.Length != 16)
Console.Error.WriteLine($"{hexKey} is not a valid key, detecting key automatically...");
else
{
Console.WriteLine($"Creating {irdPath} with Key: {Convert.ToHexString(discKey)}");
IRD ird1 = new ReIRD(isoPath, discKey, layerbreak);
ird1.Write(irdPath);
if (verbose)
ird1.Print();
return irdPath;
}
}
catch (ArgumentException)
catch (ArgumentException e)
{
Console.Error.WriteLine($"{Convert.ToHexString(discKey)} is not a valid key, detecting key automatically...");
Console.Error.WriteLine(e.Message + ", failed to create IRD");
return null;
}
catch (FileNotFoundException)
{
@@ -653,11 +758,17 @@ namespace IRDKit
try
{
Console.WriteLine($"Creating {irdPath} with key from: {getKeyLog}");
IRD ird3 = new ReIRD(isoPath, getKeyLog);
ird3.Write(irdPath);
ird3.Print();
IRD ird1 = new ReIRD(isoPath, getKeyLog);
ird1.Write(irdPath);
if (verbose)
ird1.Print();
return irdPath;
}
catch (ArgumentException e)
{
Console.Error.WriteLine(e.Message + ", failed to create IRD");
return null;
}
catch (FileNotFoundException)
{
Console.Error.WriteLine("File not found, failed to create IRD");
@@ -676,17 +787,21 @@ namespace IRDKit
// Read key from .key file
byte[] discKey = File.ReadAllBytes(keyfilePath);
if (discKey == null || discKey.Length != 16)
throw new ArgumentException(keyfilePath);
Console.WriteLine($"Creating {irdPath} with Key: {Convert.ToHexString(discKey)}");
IRD ird2 = new ReIRD(isoPath, discKey, layerbreak);
ird2.Write(irdPath);
ird2.Print();
return irdPath;
Console.Error.WriteLine($"{hexKey} is not a valid key, detecting key automatically...");
else
{
Console.WriteLine($"Creating {irdPath} with Key: {Convert.ToHexString(discKey)}");
IRD ird1 = new ReIRD(isoPath, discKey, layerbreak);
ird1.Write(irdPath);
if (verbose)
ird1.Print();
return irdPath;
}
}
catch (ArgumentException)
catch (ArgumentException e)
{
Console.Error.WriteLine("Given key file not valid, detecting key automatically...");
Console.Error.WriteLine(e.Message + ", failed to create IRD");
return null;
}
catch (FileNotFoundException)
{
@@ -704,11 +819,17 @@ namespace IRDKit
try
{
Console.WriteLine($"Creating {irdPath} with key from: {logfilePath}");
IRD ird3 = new ReIRD(isoPath, logfilePath);
ird3.Write(irdPath);
ird3.Print();
IRD ird1 = new ReIRD(isoPath, logfilePath);
ird1.Write(irdPath);
if (verbose)
ird1.Print();
return irdPath;
}
catch (ArgumentException e)
{
Console.Error.WriteLine(e.Message + ", failed to create IRD");
return null;
}
catch (FileNotFoundException)
{
Console.Error.WriteLine("File not found, failed to create IRD");
@@ -717,15 +838,18 @@ namespace IRDKit
}
// No key provided, try get key from redump.org
Console.WriteLine("No key provided... Searching for key on redump.org");
if (verbose)
Console.WriteLine("No key provided... Searching for key on redump.org");
// Compute CRC32 hash
byte[] crc32;
uint crc32UInt;
using (FileStream fs = File.OpenRead(isoPath))
{
Crc32 hasher = new();
hasher.Append(fs);
crc32 = hasher.GetCurrentHash();
crc32UInt = BitConverter.ToUInt32(crc32);
// Change endianness
Array.Reverse(crc32);
}
@@ -737,12 +861,12 @@ namespace IRDKit
int id;
if (ids.Count == 0)
{
Console.WriteLine("ISO not found in redump, cannot automatically retreive key");
Console.Error.WriteLine("ISO not found in redump and no valid key provided, cannot create IRD");
return null;
}
else if (ids.Count > 1)
{
// Compute SHA1 hash
// More than one result for the CRC32 hash, compute SHA1 hash instead
byte[] sha1;
using (FileStream fs = File.OpenRead(isoPath))
{
@@ -755,18 +879,19 @@ namespace IRDKit
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");
Console.Error.WriteLine("ISO not found in redump and no valid key provided, cannot create IRD");
return null;
}
else if (ids2.Count > 1)
{
Console.WriteLine("Cannot automatically get key from redump. Please search redump.org and run again with -k");
Console.Error.WriteLine("Cannot automatically get key from redump. Please search redump.org and run again with -k");
return null;
}
id = ids2[0];
}
else
{
// One result found, assume it is the PS3 ISO
id = ids[0];
}
@@ -774,15 +899,30 @@ namespace IRDKit
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");
Console.Error.WriteLine("Invalid key obtained from redump and no valid key provided, cannot create IRD");
return null;
}
// Create IRD with key from redump
Console.WriteLine($"Creating {irdPath} with Key: {Convert.ToHexString(key)}");
IRD ird = new ReIRD(isoPath, key, layerbreak);
ird.Write(irdPath);
ird.Print();
return irdPath;
Console.WriteLine($"Creating {irdPath} with Key from redump.org: {Convert.ToHexString(key)}");
try
{
IRD ird = new ReIRD(isoPath, key, layerbreak, crc32UInt);
ird.Write(irdPath);
if (verbose)
ird.Print();
return irdPath;
}
catch (ArgumentException e)
{
Console.Error.WriteLine(e.Message + ", failed to create IRD");
return null;
}
catch (FileNotFoundException)
{
Console.Error.WriteLine("File not found, failed to create IRD");
return null;
}
}
#endregion
+40 -6
View File
@@ -1,7 +1,41 @@
## How to use IRDKit
# How to use IRDKit
IRDKit is a tool that allows direct use of LibIRD functionality from the command line interface. The basic usage is:
```
irdkit game.iso game.ird
```
For detailed usage, run `irdkit --help`
IRDKit is a tool that allows direct use of LibIRD functionality from the command line interface.
For full help instructions, run `irdkit help`
## Creating ISOs
For all options, run `irdkit help create`
To create an IRD from an ISO, run `irdkit create game.iso`
Multiple ISOs can be processed at once with `irdkit create game1.iso game2.iso`
Or a whole directory of ISOs can be processed with `irdkit create ./ISO`, or recursively with `irdkit create -r ./ISO`
The IRD will be created in the same folder as the ISO, with the same filename.
A different IRD path and/or filename can be defined with `-o` or `--output=`
### Key
By default, IRDs will be created by pulling keys from redump.org
A key can be manually provided with `-k` or `--key=`
A key file can be provided with `-f game.key` or `--key-file=`
A key from GetKey log file can be used with `-l game.getkey.log` or `--getkey-log=`
### PIC
By default, a PIC will be generated assuming a default layerbreak
A layerbreak value can be provided with `-b` or `--layerbreak=`
A PIC from a GetKey log file can be used with `-l game.getkey.log` or `--getkey-log=`
## Printing info
For all options, run `irdkit help info`
To print info about an ISO or IRD file, run `irdkit info game.iso` or `irdkit info game.ird`
The info can be printed to a file, e.g. `-o out.txt` or `--output=`
The info can be formatted as a JSON with `-j` or `--json`
## Comparing IRDs
For all options, run `irdkit help diff`
To compare two IRDs, run `irdkit diff game1.ird game2.ird`
The comparison can be printed to a file, e.g. `-o out.txt` or `--output=`
+106 -65
View File
@@ -117,7 +117,6 @@ namespace LibIRD
}
}
private byte[] _discKey;
// TODO: Link Data1Key and Disc Key
/// <summary>
/// D1 key
@@ -271,7 +270,7 @@ namespace LibIRD
/// <summary>
/// MD5 hashes for all decrypted files in the image
/// </summary>
/// <remarks><see cref="FileHashes"/> files, 16-bytes per hash, alternating with each <see cref="FileHashes"/> entry</remarks>
/// <remarks><see cref="FileCount"/> files, 16-bytes per hash, alternating with each <see cref="FileHashes"/> entry</remarks>
public byte[][] FileHashes { get; private set; }
/// <summary>
@@ -406,7 +405,6 @@ namespace LibIRD
private protected static byte[] GenerateD1(byte[] key)
{
// Validate key
ArgumentNullException.ThrowIfNull(key, nameof(key));
if (key.Length != 16)
throw new ArgumentException("Disc Key must be a byte array of length 16", nameof(key));
@@ -440,7 +438,6 @@ namespace LibIRD
private protected static byte[] GenerateDiscKey(byte[] d1)
{
// Validate key
ArgumentNullException.ThrowIfNull(d1, nameof(d1));
if (d1.Length != 16)
throw new ArgumentException("Disc Key must be a byte array of length 16", nameof(d1));
@@ -474,7 +471,6 @@ namespace LibIRD
private protected static byte[] GenerateD2(byte[] d2)
{
// Validate id
ArgumentNullException.ThrowIfNull(d2, nameof(d2));
if (d2.Length != 16) throw new ArgumentException("Disc ID must be a byte array of length 16", nameof(d2));
// Setup AES encryption
@@ -507,7 +503,6 @@ namespace LibIRD
private protected static byte[] GenerateDiscID(byte[] d2)
{
// Validate id
ArgumentNullException.ThrowIfNull(d2 , nameof(d2));
if (d2.Length != 16)
throw new ArgumentException("Disc ID must be a byte array of length 16", nameof(d2));
@@ -540,9 +535,7 @@ namespace LibIRD
/// <exception cref="InvalidDataException"></exception>
private protected void ParseGetKeyLog(string getKeyLog)
{
// Validate .getkey.log file path
ArgumentNullException.ThrowIfNull(getKeyLog, nameof(getKeyLog));
if (!File.Exists(getKeyLog))
throw new FileNotFoundException(nameof(getKeyLog));
@@ -640,7 +633,7 @@ namespace LibIRD
ExtraConfig |= 0x01;
// Redump-style IRDs use fields from PS3_DISC.SFB
using DiscUtils.Streams.SparseStream s = reader.OpenFile("PS3_DISC.SFB", FileMode.Open, FileAccess.Read);
using SparseStream s = reader.OpenFile("PS3_DISC.SFB", FileMode.Open, FileAccess.Read);
// Parse PS3_DISC.SFB file
PS3_DiscSFB ps3_DiscSFB = new(s);
@@ -658,7 +651,7 @@ namespace LibIRD
}
// Read PS3 Metadata from PARAM.SFO
using (DiscUtils.Streams.SparseStream s = reader.OpenFile("\\PS3_GAME\\PARAM.SFO", FileMode.Open, FileAccess.Read))
using (SparseStream s = reader.OpenFile("\\PS3_GAME\\PARAM.SFO", FileMode.Open, FileAccess.Read))
{
// Parse PARAM.SFO file
ParamSFO paramSFO = new(s);
@@ -722,7 +715,6 @@ namespace LibIRD
HashFiles(fs, reader, rootDir);
if (FileCount != fileCount)
{
Console.WriteLine($"Likely contains non-contiguous files: detected {FileCount} out of {fileCount} expected files");
long[] tempFileKeys = FileKeys;
Array.Resize(ref tempFileKeys, (int)FileCount);
FileKeys = tempFileKeys;
@@ -744,7 +736,7 @@ namespace LibIRD
private void GetSystemVersion(FileStream fs, CDReader reader)
{
// Determine PUP file offset via cluster
DiscUtils.Streams.Range<long, long>[] updateClusters = reader.PathToClusters("\\PS3_UPDATE\\PS3UPDAT.PUP");
Range<long, long>[] updateClusters = reader.PathToClusters("\\PS3_UPDATE\\PS3UPDAT.PUP");
if (updateClusters == null && updateClusters.Length == 0 && updateClusters[0] == null)
throw new InvalidFileSystemException("Invalid file extents for PS3UPDAT.PUP");
@@ -787,7 +779,7 @@ namespace LibIRD
private void GetHeader(FileStream fs, CDReader reader)
{
// Determine the extent of the header via cluster (Sector 0 to first data sector)
DiscUtils.Streams.Range<long, long>[] sfbClusters = reader.PathToClusters("\\PS3_DISC.SFB");
Range<long, long>[] sfbClusters = reader.PathToClusters("\\PS3_DISC.SFB");
if (sfbClusters == null && sfbClusters.Length == 0 && sfbClusters[0] == null)
throw new InvalidFileSystemException("Invalid file extents for PS3_DISC.SFB");
// End of header is at beginning of first byte of dedicated cluster
@@ -795,7 +787,11 @@ namespace LibIRD
// Begin a GZip stream to write header to
using MemoryStream headerStream = new();
#if NET6_0_OR_GREATER
using (GZipStream gzs = new(headerStream, CompressionLevel.SmallestSize))
#else
using (GZipStream gzs = new(headerStream, CompressionLevel.Optimal))
#endif
{
// Start reading data from the beginning of the ISO file
fs.Seek(0, SeekOrigin.Begin);
@@ -823,7 +819,11 @@ namespace LibIRD
{
// Begin a GZip stream to write footer to
using MemoryStream footerStream = new();
#if NET6_0_OR_GREATER
using (GZipStream gzs = new(footerStream, CompressionLevel.SmallestSize))
#else
using (GZipStream gzs = new(footerStream, CompressionLevel.Optimal))
#endif
{
// Start reading data from after last file (PS3UPDAT.PUP)
fs.Seek(UpdateEnd, SeekOrigin.Begin);
@@ -890,8 +890,8 @@ namespace LibIRD
RegionEnd[^1] = (UpdateEnd / SectorSize) - 1;
// Determine MD5 hashes for each region
using MD5 md5 = MD5.Create();
byte[] buf = new byte[SectorSize];
int bufSectors = 1024;
byte[] buf = new byte[bufSectors * SectorSize];
for (int i = 0; i < RegionCount; i++)
{
// Start reading data from first sector of region
@@ -899,19 +899,32 @@ namespace LibIRD
// Compute MD5 hash for just the region portion of the ISO file
int numBytes;
for (long j = RegionStart[i]; j <= RegionEnd[i]; j++)
using MD5 md5 = MD5.Create();
int regionSectors = (int)(RegionEnd[i] - RegionStart[i]) + 1;
for (int j = bufSectors; j <= regionSectors; j += bufSectors)
{
// Read one sector at a time
// Read into buffer
numBytes = fs.Read(buf, 0, buf.Length);
// Check that an entire sector was read
// TODO: Process partial buffer if non-zero is returned
if (numBytes < buf.Length)
throw new InvalidFileSystemException("Disc region ended unexpectedly");
// Process MD5 sum one sector at a time
// Process MD5 sum
md5.TransformBlock(buf, 0, buf.Length, null, 0);
}
// Read any remaining sectors
int bufRemainder = (int)(SectorSize * (regionSectors % bufSectors));
if (bufRemainder != 0)
{
numBytes = fs.Read(buf, 0, bufRemainder);
// TODO: Process partial buffer if non-zero is returned
if (numBytes < bufRemainder)
throw new InvalidFileSystemException("Disc region ended unexpectedly");
}
// Compute and store MD5 hash of region
md5.TransformFinalBlock(buf, 0, 0);
md5.TransformFinalBlock(buf, 0, bufRemainder);
RegionHashes[i] = md5.Hash;
}
}
@@ -929,7 +942,7 @@ namespace LibIRD
string filePath = fileInfo.FullName;
// Determine the extents of the file via clusters
DiscUtils.Streams.Range<long, long>[] fileClusters = reader.PathToClusters(filePath);
Range<long, long>[] fileClusters = reader.PathToClusters(filePath);
// If invalid clusters were returned, we can't hash this file
if (fileClusters == null && fileClusters.Length == 0)
@@ -937,67 +950,80 @@ namespace LibIRD
// Determine smallest file offset as first sector
long smallestOffset = fileClusters[0].Offset;
bool nonContiguous = false;
for (int i = 1; i < fileClusters.Length; i++)
{
if (fileClusters[i] == null)
throw new InvalidFileSystemException($"Unexpected file extents for {filePath}");
if (fileClusters[i].Offset * SectorSize != fileClusters[i - 1].Offset * SectorSize + fileClusters[i - 1].Count)
nonContiguous = true;
if (fileClusters[i].Offset < smallestOffset)
smallestOffset = fileClusters[i].Offset;
}
int firstSector = (int)(smallestOffset);
// If already encountered file offset, skip this file
if (Array.Exists(FileKeys, element => element == firstSector))
if (Array.Exists(FileKeys, element => element == smallestOffset))
continue;
else if (nonContiguous)
Console.WriteLine($"Non-contiguous file found: {filePath}");
// Add file offset to keys
FileKeys[FileCount] = firstSector;
FileKeys[FileCount] = smallestOffset;
// Determine whether file is in encrypted or decrypted region
bool encrypted = false;
for (int i = RegionCount - 1; i > 0; i--)
{
if (RegionStart[i] <= firstSector)
if (RegionStart[i] <= smallestOffset)
{
encrypted = i % 2 == 1;
break;
}
}
// Hash each non-contiguous portion of the ISO file
byte[] buf = new byte[SectorSize];
MD5 md5 = MD5.Create();
// Read one sector at a time for small files
int bufSectors = (fileClusters[0].Count < 1024 * SectorSize) ? 1 : 1024;
byte[] buf = new byte[bufSectors * SectorSize];
// Hash each non-contiguous portion of the file
using MD5 md5 = MD5.Create();
for (int i = 0; i < fileClusters.Length; i++)
{
// Start reading data from the beginning of the ISO file
// Start reading data from the beginning of the current extent
fs.Seek(fileClusters[i].Offset * SectorSize, SeekOrigin.Begin);
int numBytes;
// Read all data before the first data sector
for (int j = 0; j < (fileClusters[i].Count / SectorSize); j++)
// Read file in buffers
long fileSectors = fileClusters[i].Count / SectorSize;
for (int j = 0; j <= fileSectors - bufSectors; j += bufSectors)
{
numBytes = fs.Read(buf, 0, buf.Length);
// Check that an entire sector was read
if (numBytes < buf.Length)
// TODO: Process partial buffer if non-zero is returned
if (numBytes != buf.Length)
throw new InvalidFileSystemException("Disc region ended unexpectedly");
// Decrypt sector if necessary
// Decrypt buffer if necessary
if (encrypted)
buf = DecryptSector(buf, firstSector + j);
DecryptSectors(ref buf, (int)fileClusters[i].Offset + j);
// Hash sector
md5.TransformBlock(buf, 0, numBytes, null, 0);
md5.TransformBlock(buf, 0, buf.Length, null, 0);
}
// Read remaining partial sector
if (fileClusters[i].Count % SectorSize != 0)
// Read remaining partial buffer
if ((fileClusters[i].Count % buf.Length) > 0)
{
numBytes = fs.Read(buf, 0, buf.Length);
// Check that an entire sector was read
if (numBytes < buf.Length)
// TODO: Process partial buffer if non-zero is returned
if (numBytes != buf.Length)
throw new InvalidFileSystemException("Disc region ended unexpectedly");
// Decrypt partial sector if necessary
// Decrypt buffer if necessary
if (encrypted)
buf = DecryptSector(buf, firstSector + (int)(fileClusters[i].Count / SectorSize));
// Hash partial sector
md5.TransformBlock(buf, 0, (int)(fileClusters[i].Count % SectorSize), null, 0);
DecryptSectors(ref buf, (int)fileClusters[i].Offset + bufSectors * (int)(fileClusters[i].Count / buf.Length));
// Hash partial buffer
md5.TransformBlock(buf, 0, (int)(fileClusters[i].Count % buf.Length), null, 0);
}
}
@@ -1015,38 +1041,49 @@ namespace LibIRD
}
/// <summary>
/// Decrypts a given sector byte array
/// Decrypts a given byte array of sector(s)
/// </summary>
/// <param name="sector">Byte array to be decrypted</param>
/// <param name="buffer">Byte array to be decrypted</param>
/// <param name="offset">Number of bytes to decrypt</param>
/// <exception cref="InvalidOperationException"></exception>
private protected byte[] DecryptSector(byte[] sector, int sectorNumber)
private protected void DecryptSectors(ref byte[] buffer, int sectorNumber)
{
ArgumentNullException.ThrowIfNull(buffer);
if (buffer.Length == 0 || buffer.Length % SectorSize != 0)
throw new ArgumentException("Encrypted buffer must be multiple of SectorSize");
// Setup AES decryption
using Aes aes = Aes.Create() ?? throw new InvalidOperationException("AES not available. Change your system settings");
// Set AES settings
aes.Key = DiscKey;
aes.Padding = PaddingMode.None;
aes.Mode = CipherMode.CBC;
// Determine Initial Value based on sector number
byte[] iv = new byte[16];
for (int i = 0; i < 16; i++)
// Decrypt buffer one sector at a time
for (int i = 0; i < buffer.Length; i += (int)SectorSize)
{
byte a = (byte)(sectorNumber & 0xFF);
iv[16 - i - 1] = (byte)(sectorNumber & 0xFF);
sectorNumber >>= 8;
// Determine AES Initial Value based on sector number
byte[] iv = new byte[16];
int tempNum = sectorNumber;
for (int j = 0; j < 16; j++)
{
iv[16 - j - 1] = (byte)(tempNum & 0xFF);
tempNum >>= 8;
}
aes.IV = iv;
// Perform AES decryption
using MemoryStream stream = new();
using CryptoStream cs = new(stream, aes.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(buffer, i, (int)SectorSize);
cs.FlushFinalBlock();
// Write decrypted sector to output
stream.ToArray().CopyTo(buffer, i);
sectorNumber++;
}
aes.IV = iv;
// Perform AES decryption
using MemoryStream stream = new();
using ICryptoTransform dec = aes.CreateDecryptor();
using CryptoStream cs = new(stream, dec, CryptoStreamMode.Write);
cs.Write(sector, 0, sector.Length);
cs.FlushFinalBlock();
return stream.ToArray();
return;
}
/// <summary>
@@ -1175,7 +1212,11 @@ namespace LibIRD
// Create the IRD file stream
using FileStream fs = new(irdPath, FileMode.Create, FileAccess.Write);
// Create a GZipped IRD file stream
#if NET6_0_OR_GREATER
using GZipStream gzStream = new(fs, CompressionLevel.SmallestSize);
#else
using GZipStream gzStream = new(fs, CompressionLevel.Optimal);
#endif
// Write entire gzipped IRD stream to file
stream.Position = 0;
stream.CopyTo(gzStream);
@@ -1242,7 +1283,7 @@ namespace LibIRD
uint fileCount = br.ReadUInt32();
long[] fileKeys = new long[fileCount];
byte[][] fileHashes = new byte[fileCount][];
for (int i = 0; i < fileCount; i++)
for (int i = 0; i < fileCount; i++)
{
fileKeys[i] = br.ReadInt64();
fileHashes[i] = br.ReadBytes(16);
+16 -6
View File
@@ -2,16 +2,17 @@
<PropertyGroup>
<!-- Assembly Properties -->
<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>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<Version>0.3.0</Version>
<Version>0.5.0</Version>
<PackageOutputPath>../nupkg</PackageOutputPath>
<!-- Package Properties -->
<Authors>Deterous</Authors>
<Description>Library for ISO Rebuild Data</Description>
<Copyright>Copyright (c) Deterous 2024</Copyright>
<Copyright>Copyright (c) Deterous 2023-2024</Copyright>
<PackageReadmeFile>README.md</PackageReadmeFile>
<RepositoryUrl>https://github.com/Deterous/LibIRD/</RepositoryUrl>
<RepositoryType>git</RepositoryType>
@@ -25,10 +26,19 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DiscUtils\Library\DiscUtils.Core\DiscUtils.Core.csproj" />
<ProjectReference Include="..\DiscUtils\Library\DiscUtils.Iso9660\DiscUtils.Iso9660.csproj" />
<ProjectReference Include="..\DiscUtils\Library\DiscUtils.Streams\DiscUtils.Streams.csproj" />
<ProjectReference Include="..\DiscUtils\Library\DiscUtils.Core\DiscUtils.Core.csproj" PrivateAssets="All" />
<ProjectReference Include="..\DiscUtils\Library\DiscUtils.Iso9660\DiscUtils.Iso9660.csproj" PrivateAssets="All" />
<ProjectReference Include="..\DiscUtils\Library\DiscUtils.Streams\DiscUtils.Streams.csproj" PrivateAssets="All" />
<PackageReference Include="System.IO.Hashing" Version="8.0.0" />
</ItemGroup>
<PropertyGroup>
<TargetsForTfmSpecificBuildOutput>$(TargetsForTfmSpecificBuildOutput);CopyProjectReferencesToPackage</TargetsForTfmSpecificBuildOutput>
</PropertyGroup>
<Target Name="CopyProjectReferencesToPackage" DependsOnTargets="BuildOnlySettings;ResolveReferences">
<ItemGroup>
<BuildOutputInPackage Include="@(ReferenceCopyLocalPaths-&gt;WithMetadataValue('ReferenceSourceTarget', 'ProjectReference')-&gt;WithMetadataValue('PrivateAssets', 'All'))" />
</ItemGroup>
</Target>
</Project>
+7 -6
View File
@@ -27,18 +27,14 @@ namespace LibIRD
/// A field within the PS3_DISC.SFB file
/// </summary>
/// <remarks>string Key, string Value</remarks>
public Dictionary<string, string> Field { get; private set; }
public Dictionary<string, string> Field { get; private set; }
/// <summary>
/// Constructor using a PARAM.SFO file path
/// </summary>
/// <param name="sfbPath">Full file path to the PS3_DISC.SFB file</param>
/// <exception cref="ArgumentNullException"></exception>
public PS3_DiscSFB(string sfbPath)
{
// Validate file path
ArgumentNullException.ThrowIfNull(sfbPath, nameof(sfbPath));
// Read file as a stream, and parse file
using FileStream fs = new(sfbPath, FileMode.Open, FileAccess.Read);
Parse(fs);
@@ -135,6 +131,11 @@ namespace LibIRD
}
}
/// <summary>
/// Define JSON options once
/// </summary>
private readonly JsonSerializerOptions JsonOpts = new() { WriteIndented = true };
/// <summary>
/// Prints parameters extracted from PS3_DISC.SFB to a json object
/// </summary>
@@ -142,7 +143,7 @@ namespace LibIRD
public void PrintJson(string jsonPath = null)
{
// Serialise PS3_Disc.SFB data to a JSON object
string json = JsonSerializer.Serialize(Field, new JsonSerializerOptions { WriteIndented = true });
string json = JsonSerializer.Serialize(Field, JsonOpts);
// If no path given, output to console
if (jsonPath == null)
+10 -10
View File
@@ -43,13 +43,8 @@ namespace LibIRD
/// Constructor using a PARAM.SFO file path
/// </summary>
/// <param name="sfoPath">Full file path to the PARAM.SFO file</param>
/// <exception cref="ArgumentNullException"></exception>
public ParamSFO(string sfoPath)
{
// Validate file path
if (sfoPath == null || sfoPath.Length <= 0)
throw new ArgumentNullException(nameof(sfoPath));
// Read file as a stream, and parse file
using FileStream fs = new(sfoPath, FileMode.Open, FileAccess.Read);
Parse(fs);
@@ -103,7 +98,7 @@ namespace LibIRD
- keyOffset[i];
// Read ith key name
string key = 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
sfoStream.Position = dataTableStart + dataOffset[i];
@@ -112,13 +107,13 @@ namespace LibIRD
Field[key] = dataFormat[i] switch
{
// Non-null-terminated UTF-8 String
0x0004 => Encoding.UTF8.GetString(br.ReadBytes((int) dataLength[i])),
0x0004 => Encoding.UTF8.GetString(br.ReadBytes((int)dataLength[i])),
// Null-terminated UTF-8 String
0x0204 => Encoding.UTF8.GetString(br.ReadBytes((int) dataLength[i])).TrimEnd('\0'),
0x0204 => Encoding.UTF8.GetString(br.ReadBytes((int)dataLength[i])).TrimEnd('\0'),
// Integer
0x0404 => br.ReadInt32().ToString(),
// Unknown data format, assume null-terminated string
_ => Encoding.UTF8.GetString(br.ReadBytes((int) dataLength[i])).TrimEnd('\0'),
_ => Encoding.UTF8.GetString(br.ReadBytes((int)dataLength[i])).TrimEnd('\0'),
};
}
}
@@ -159,6 +154,11 @@ namespace LibIRD
}
}
/// <summary>
/// Define JSON options once
/// </summary>
private readonly JsonSerializerOptions JsonOpts = new() { WriteIndented = true };
/// <summary>
/// Prints parameters extracted from PARAM.SFO to a json object
/// </summary>
@@ -166,7 +166,7 @@ namespace LibIRD
public void PrintJson(string jsonPath = null)
{
// Serialise PS3_Disc.SFB data to a JSON object
string json = JsonSerializer.Serialize(Field, new JsonSerializerOptions { WriteIndented = true });
string json = JsonSerializer.Serialize(Field, JsonOpts);
// If no path given, output to console
if (jsonPath == null)
+81 -85
View File
@@ -1,4 +1,5 @@
using System;
using DiscUtils.Iso9660;
using System;
using System.IO;
using System.IO.Hashing;
@@ -51,15 +52,6 @@ namespace LibIRD
/// </summary>
public class ReIRD : IRD
{
#region Properties
/// <summary>
/// ISO file size
/// </summary>
private long Size { get; set; }
#endregion
#region Constructors
/// <summary>
@@ -67,25 +59,10 @@ namespace LibIRD
/// </summary>
/// <param name="isoPath">Path to the ISO</param>
/// <param name="getKeyLog">Path to the GetKey log file</param>
/// <param name="layerbreak">Layerbreak value, in sectors</param>
/// <exception cref="InvalidDataException"></exception>
public ReIRD(string isoPath, string getKeyLog, long? layerbreak = null) : base(isoPath, getKeyLog, true)
public ReIRD(string isoPath, string getKeyLog) : base(isoPath, getKeyLog, true)
{
// Generate Unique Identifier using ISO CRC32
UID = GenerateUID(isoPath);
// Determine ISO file size
Size = CalculateSize(isoPath);
// Generate Data 2 using Disc ID
DiscID = GenerateID(Size);
// Generate Disc PIC
byte[] pic = GeneratePIC(Size, layerbreak * SectorSize);
// Check that GetKey log matches expected PIC
if (!((ReadOnlySpan<byte>)PIC).SequenceEqual(pic))
throw new InvalidDataException("Unexpected PIC in .getkey.log");
}
/// <summary>
@@ -94,23 +71,24 @@ namespace LibIRD
/// <param name="isoPath">Path to the ISO</param>
/// <param name="key">Disc Key, redump-style (AES encrypted Data 1)</param>
/// <param name="layerbreak">Layerbreak value, in sectors</param>
/// <param name="uid">Unique ID, crc32 hash of ISO</param>
/// <param name="region">Disc Region</param>
public ReIRD(string isoPath, byte[] key, long? layerbreak = null, Region region = Region.NONE) : base()
public ReIRD(string isoPath, byte[] key, long? layerbreak = null, uint? uid = null, Region region = Region.NONE) : base()
{
// Generate Unique Identifier using ISO CRC32
UID = GenerateUID(isoPath);
UID = uid == null ? GenerateUID(isoPath) : (uint)uid;
// Determine ISO file size
Size = CalculateSize(isoPath);
long size = CalculateSize(isoPath);
// Set Disc Key
DiscKey = key;
// Generate Data 2 using Disc ID
DiscID = GenerateID(Size, region);
DiscID = GenerateID(size, region);
// Generate Disc PIC
PIC = GeneratePIC(Size, layerbreak * SectorSize);
PIC = GeneratePIC(isoPath, size, layerbreak * SectorSize);
// Generate IRD fields
GenerateIRD(isoPath, true);
@@ -143,12 +121,13 @@ namespace LibIRD
/// <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>
/// <exception cref="ArgumentException"></exception>
private static byte[] GeneratePIC(long size, long? layerbreak = null, bool exactIRD = false)
private static byte[] GeneratePIC(string isoPath, long size, long? layerbreak = null, bool exactIRD = false)
{
// Validate size
if (size <= 0 || (size % SectorSize) != 0)
throw new ArgumentException("ISO Size in bytes must be a positive integer multiple of 2048", nameof(size));
// Validate layerbreak
// Validate provided layerbreak
if (layerbreak != null)
{
if (layerbreak <= 0 || (layerbreak >= size))
@@ -156,70 +135,78 @@ namespace LibIRD
if (layerbreak >= 2 * BDLayerSize || layerbreak % SectorSize != 0)
throw new ArgumentException("Unexpected layerbreak value", nameof(size));
}
// If layerbreak value was not set, assume it is a non-hybrid disc with default layerbreak
long layer_break = layerbreak ?? BDLayerSize;
else
{
// If no layerbreak provided, ensure ISO is not BD-Video hybrid
using FileStream fs = new FileStream(isoPath, FileMode.Open, FileAccess.Read) ?? throw new FileNotFoundException(isoPath);
CDReader reader = new(fs, true, true);
if (reader.DirectoryExists("\\BDMV"))
throw new ArgumentException("Layerbreak must be provided for BD-Video hybrid discs");
// Assume disc has default layerbreak
layerbreak = BDLayerSize;
}
// Generate the PIC based on the size and layerbreak of the ISO
byte[] pic;
if (size > BDLayerSize) // if BD-50
{
// Layer 0 start sector = 0x01000000
long l0_start_sector = 1048576;
// Layer 0 end sector = start sector + layerbreak - 2
long l0_end_sector = (layer_break / SectorSize) + l0_start_sector - 2;
// Convert end sector location to hex values for PIC
byte[] l0es = [(byte)((l0_end_sector >> 24) & 0xFF),
(byte)((l0_end_sector >> 16) & 0xFF),
(byte)((l0_end_sector >> 8) & 0xFF),
(byte)((l0_end_sector >> 0) & 0xFF)];
long l0_start_sector = 1048576;
// Layer 0 end sector = start sector + layerbreak - 2
long l0_end_sector = ((long)layerbreak / SectorSize) + l0_start_sector - 2;
// Convert end sector location to hex values for PIC
byte[] l0es = [(byte)((l0_end_sector >> 24) & 0xFF),
(byte)((l0_end_sector >> 16) & 0xFF),
(byte)((l0_end_sector >> 8) & 0xFF),
(byte)((l0_end_sector >> 0) & 0xFF)];
// Layer 1 start sector = end of disc (0x01EFFFFE) - layerbreak + 2
long l1_start_sector = 32505854 - (layer_break / SectorSize) + 2;
// Convert start of start sector location to hex values for PIC
byte[] l1ss = [(byte)((l1_start_sector >> 24) & 0xFF),
(byte)((l1_start_sector >> 16) & 0xFF),
(byte)((l1_start_sector >> 8) & 0xFF),
(byte)((l1_start_sector >> 0) & 0xFF)];
// Total sectors used = num_sectors + Layer 0 start + sectors_between_layers (usually 0x01358C00 - 0x00CA73FE - 3)
long total_sectors = (size / SectorSize) + l0_start_sector + (l1_start_sector - l0_end_sector - 3);
byte[] ts = BitConverter.GetBytes((uint) total_sectors);
long l1_start_sector = 32505854 - ((long)layerbreak! / SectorSize) + 2;
// Convert start of start sector location to hex values for PIC
byte[] l1ss = [(byte)((l1_start_sector >> 24) & 0xFF),
(byte)((l1_start_sector >> 16) & 0xFF),
(byte)((l1_start_sector >> 8) & 0xFF),
(byte)((l1_start_sector >> 0) & 0xFF)];
// Define the PIC
pic = [
// Initial portion of PIC (24 bytes)
// [4098 bytes] [2x 0x00] ["DI"] [v1] [10units] [DI num]
// Total sectors used = num_sectors + Layer 0 start + sectors_between_layers (usually 0x01358C00 - 0x00CA73FE - 3)
long total_sectors = (size / SectorSize) + l0_start_sector + (l1_start_sector - l0_end_sector - 3);
byte[] ts = BitConverter.GetBytes((uint)total_sectors);
// Define the PIC
pic = [
// Initial portion of PIC (24 bytes)
// [4098 bytes] [2x 0x00] ["DI"] [v1] [10units] [DI num]
0x10, 0x02, 0x00, 0x00, 0x44, 0x49, 0x01, 0x10, 0x00, 0x00, 0x20, 0x00,
// ["BDR"] [2 layers]
// ["BDR"] [2 layers]
0x42, 0x44, 0x4F, 0x01, 0x21, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
// Total sectors used on disc (4 bytes)
// Total sectors used on disc (4 bytes)
ts[3], ts[2], ts[1], ts[0],
// 1st Layer sector start location (4 bytes)
// 1st Layer sector start location (4 bytes)
0x00, 0x10, 0x00, 0x00,
// 1st Layer sector end location (4 bytes), 0x00CA73FE for default BD layerbreak of 12219392
// 1st Layer sector end location (4 bytes), 0x00CA73FE for default BD layerbreak of 12219392
l0es[0], l0es[1], l0es[2], l0es[3],
// 32 bytes of zeros
// 32 bytes of zeros
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// Initial portion of PIC again, for 2nd layer
// ["DI"] [v1] [11unit][DI num]
// Initial portion of PIC again, for 2nd layer
// ["DI"] [v1] [11unit][DI num]
0x44, 0x49, 0x01, 0x11, 0x00, 0x01, 0x20, 0x00,
// ["BDR"] [2 layers]
// ["BDR"] [2 layers]
0x42, 0x44, 0x4F, 0x01, 0x21, 0x01, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
// Total sectors used on disc
// Total sectors used on disc
ts[3], ts[2], ts[1], ts[0],
// 2nd Layer sector start location, 0x01358C00 for default BD layerbreak of 12219392
// 2nd Layer sector start location, 0x01358C00 for default BD layerbreak of 12219392
l1ss[0], l1ss[1], l1ss[2], l1ss[3],
// 2nd Layer sector end location
// 2nd Layer sector end location
0x01, 0xEF, 0xFF, 0xFE,
// Remaining 32 bytes are zeroes
// Remaining 32 bytes are zeroes
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ];
// 3k3y style: 0x03 at last byte
if (exactIRD)
pic[114] = 0x03;
// 3k3y style: 0x03 at last byte
if (exactIRD)
pic[114] = 0x03;
}
}
else // if BD-25
{
// Total sectors used on disc: num_sectors + layer_sector_end (0x00100000) - 1
@@ -245,7 +232,7 @@ namespace LibIRD
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ];
}
return pic;
}
@@ -253,15 +240,19 @@ namespace LibIRD
/// Generates the UID field by computing the CRC32 hash of the ISO
/// </summary>
/// <param name="isoPath">Path to the ISO</param>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="FileNotFoundException"></exception>
private static uint GenerateUID(string isoPath)
{
// Validate ISO path
ArgumentNullException.ThrowIfNull(isoPath, nameof(isoPath));
// Check file exists
var iso = new FileInfo(isoPath);
FileInfo iso;
try
{
iso = new FileInfo(isoPath);
}
catch (Exception e)
{
throw new ArgumentException("Invalid ISO Path: " + e.Message);
}
if (!iso.Exists)
throw new FileNotFoundException(nameof(isoPath));
@@ -282,15 +273,20 @@ namespace LibIRD
/// Calculates ISO file size
/// </summary>
/// <param name="isoPath">Path to the ISO</param>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="FileNotFoundException"></exception>
private static long CalculateSize(string isoPath)
{
// Validate ISO path
ArgumentNullException.ThrowIfNull(isoPath, nameof(isoPath));
// Check file exists
var iso = new FileInfo(isoPath);
FileInfo iso;
try
{
iso = new FileInfo(isoPath);
}
catch (Exception e)
{
throw new ArgumentException("Invalid ISO Path: " + e.Message);
}
if (!iso.Exists)
throw new FileNotFoundException(nameof(isoPath));
+1
View File
@@ -13,6 +13,7 @@ IRDKit is a tool that allows direct use of LibIRD functionality from a command l
- Printing info about all ISOs and IRDs in a folder: `irdkit info .`
- Creating an IRD from an ISO: `irdkit create game.iso`
- Finding differences between two IRDs: `irdkit diff game1.ird game2.ird`
For detailed usage, read more [here](IRDKit).
## Using the LibIRD library
+15
View File
@@ -0,0 +1,15 @@
dotnet publish -c Release -f net8.0 -r win-x86 --self-contained=false -p:PublishSingleFile=true -p:DebugType=None IRDKit\IRDKit.csproj
dotnet publish -c Release -f net8.0 -r win-x64 --self-contained=false -p:PublishSingleFile=true -p:DebugType=None IRDKit\IRDKit.csproj
dotnet publish -c Release -f net8.0 -r win-arm64 --self-contained=false -p:PublishSingleFile=true -p:DebugType=None IRDKit\IRDKit.csproj
dotnet publish -c Release -f net8.0 -r linux-x64 --self-contained=false -p:PublishSingleFile=true -p:DebugType=None IRDKit\IRDKit.csproj
dotnet publish -c Release -f net8.0 -r linux-arm64 --self-contained=false -p:PublishSingleFile=true -p:DebugType=None IRDKit\IRDKit.csproj
dotnet publish -c Release -f net8.0 -r osx-x64 --self-contained=false -p:PublishSingleFile=true -p:DebugType=None IRDKit\IRDKit.csproj
dotnet publish -c Release -f net8.0 -r osx-arm64 --self-contained=false -p:PublishSingleFile=true -p:DebugType=None IRDKit\IRDKit.csproj
Compress-Archive -Path "./IRDKit/bin/Release/net8.0/win-x86/publish/irdkit.exe" -Destination "./irdkit-win-x86.zip" -CompressionLevel "Optimal"
Compress-Archive -Path "./IRDKit/bin/Release/net8.0/win-x64/publish/irdkit.exe" -Destination "./irdkit-win-x64.zip" -CompressionLevel "Optimal"
Compress-Archive -Path "./IRDKit/bin/Release/net8.0/win-arm64/publish/irdkit.exe" -Destination "./irdkit-win-arm64.zip" -CompressionLevel "Optimal"
Compress-Archive -Path "./IRDKit/bin/Release/net8.0/linux-x64/publish/irdkit" -Destination "./irdkit-linux-x64.zip" -CompressionLevel "Optimal"
Compress-Archive -Path "./IRDKit/bin/Release/net8.0/linux-arm64/publish/irdkit" -Destination "./irdkit-linux-arm64.zip" -CompressionLevel "Optimal"
Compress-Archive -Path "./IRDKit/bin/Release/net8.0/osx-x64/publish/irdkit" -Destination "./irdkit-osx-x64.zip" -CompressionLevel "Optimal"
Compress-Archive -Path "./IRDKit/bin/Release/net8.0/osx-arm64/publish/irdkit" -Destination "./irdkit-osx-arm64.zip" -CompressionLevel "Optimal"