Files

457 lines
16 KiB
C#
Raw Permalink Normal View History

2022-12-24 13:49:03 -08:00
using System;
using System.IO;
2022-12-24 15:25:56 -08:00
using System.Linq;
2023-01-13 14:04:21 -08:00
using System.Text;
2023-03-07 12:04:48 -05:00
using BinaryObjectScanner.Utilities;
2023-03-07 16:59:14 -05:00
using static BinaryObjectScanner.Models.VPK.Constants;
2022-12-24 13:49:03 -08:00
2023-03-07 16:59:14 -05:00
namespace BinaryObjectScanner.Wrappers
2022-12-24 13:49:03 -08:00
{
public class VPK : WrapperBase
{
2023-01-18 11:18:53 -08:00
#region Descriptive Properties
/// <inheritdoc/>
public override string Description => "Valve Package File (VPK)";
#endregion
2022-12-24 13:49:03 -08:00
#region Pass-Through Properties
#region Header
/// <inheritdoc cref="Models.VPK.Header.Signature"/>
public uint Signature => _file.Header.Signature;
/// <inheritdoc cref="Models.VPK.Header.Version"/>
public uint Version => _file.Header.Version;
/// <inheritdoc cref="Models.VPK.Header.DirectoryLength"/>
public uint DirectoryLength => _file.Header.DirectoryLength;
#endregion
#region Extended Header
/// <inheritdoc cref="Models.VPK.ExtendedHeader.Dummy0"/>
public uint? Dummy0 => _file.ExtendedHeader?.Dummy0;
/// <inheritdoc cref="Models.VPK.ExtendedHeader.ArchiveHashLength"/>
public uint? ArchiveHashLength => _file.ExtendedHeader?.ArchiveHashLength;
/// <inheritdoc cref="Models.VPK.ExtendedHeader.ExtraLength"/>
public uint? ExtraLength => _file.ExtendedHeader?.ExtraLength;
/// <inheritdoc cref="Models.VPK.ExtendedHeader.Dummy1"/>
public uint? Dummy1 => _file.ExtendedHeader?.Dummy1;
#endregion
#region Archive Hashes
/// <inheritdoc cref="Models.VPK.ArchiveHashes"/>
public Models.VPK.ArchiveHash[] ArchiveHashes => _file.ArchiveHashes;
#endregion
#region Directory Items
/// <inheritdoc cref="Models.VPK.DirectoryItems"/>
public Models.VPK.DirectoryItem[] DirectoryItems => _file.DirectoryItems;
#endregion
#endregion
#region Extension Properties
2022-12-24 15:25:56 -08:00
/// <summary>
/// Array of archive filenames attached to the given VPK
/// </summary>
public string[] ArchiveFilenames
{
get
{
// Use the cached value if we have it
if (_archiveFilenames != null)
return _archiveFilenames;
// If we don't have a source filename
if (!(_streamData is FileStream fs) || string.IsNullOrWhiteSpace(fs.Name))
return null;
// If the filename is not the right format
string extension = Path.GetExtension(fs.Name).TrimStart('.');
string fileName = Path.Combine(Path.GetDirectoryName(fs.Name), Path.GetFileNameWithoutExtension(fs.Name));
if (fileName.Length < 3)
return null;
else if (fileName.Substring(fileName.Length - 3) != "dir")
return null;
// Get the archive count
int archiveCount = DirectoryItems
.Select(di => di.DirectoryEntry)
.Select(de => de.ArchiveIndex)
2022-12-28 15:27:10 -08:00
.Where(ai => ai != HL_VPK_NO_ARCHIVE)
2022-12-24 15:25:56 -08:00
.Max();
// Build the list of archive filenames to populate
_archiveFilenames = new string[archiveCount];
// Loop through and create the archive filenames
for (int i = 0; i < archiveCount; i++)
{
// We need 5 digits to print a short, but we already have 3 for dir.
string archiveFileName = $"{fileName.Substring(0, fileName.Length - 3)}{i.ToString().PadLeft(3, '0')}.{extension}";
_archiveFilenames[i] = archiveFileName;
}
// Return the array
return _archiveFilenames;
}
}
2022-12-24 13:49:03 -08:00
#endregion
#region Instance Variables
/// <summary>
2022-12-24 20:15:58 -08:00
/// Internal representation of the VPK
2022-12-24 13:49:03 -08:00
/// </summary>
private Models.VPK.File _file;
2022-12-24 15:25:56 -08:00
/// <summary>
/// Array of archive filenames attached to the given VPK
/// </summary>
private string[] _archiveFilenames = null;
2022-12-24 13:49:03 -08:00
#endregion
#region Constructors
/// <summary>
/// Private constructor
/// </summary>
private VPK() { }
/// <summary>
2022-12-25 21:27:06 -08:00
/// Create a VPK from a byte array and offset
2022-12-24 13:49:03 -08:00
/// </summary>
2022-12-24 20:15:58 -08:00
/// <param name="data">Byte array representing the VPK</param>
2022-12-24 13:49:03 -08:00
/// <param name="offset">Offset within the array to parse</param>
2022-12-25 21:27:06 -08:00
/// <returns>A VPK wrapper on success, null on failure</returns>
2022-12-24 13:49:03 -08:00
public static VPK Create(byte[] data, int offset)
{
// If the data is invalid
if (data == null)
return null;
// If the offset is out of bounds
if (offset < 0 || offset >= data.Length)
return null;
// Create a memory stream and use that
MemoryStream dataStream = new MemoryStream(data, offset, data.Length - offset);
return Create(dataStream);
}
/// <summary>
2022-12-25 21:27:06 -08:00
/// Create a VPK from a Stream
2022-12-24 13:49:03 -08:00
/// </summary>
2022-12-25 21:27:06 -08:00
/// <param name="data">Stream representing the VPK</param>
/// <returns>A VPK wrapper on success, null on failure</returns>
2022-12-24 13:49:03 -08:00
public static VPK Create(Stream data)
{
// If the data is invalid
if (data == null || data.Length == 0 || !data.CanSeek || !data.CanRead)
return null;
var file = Builders.VPK.ParseFile(data);
if (file == null)
return null;
var wrapper = new VPK
{
_file = file,
_dataSource = DataSource.Stream,
_streamData = data,
};
return wrapper;
}
#endregion
#region Printing
/// <inheritdoc/>
2023-01-13 14:04:21 -08:00
public override StringBuilder PrettyPrint()
2022-12-24 13:49:03 -08:00
{
2023-01-13 14:04:21 -08:00
StringBuilder builder = new StringBuilder();
builder.AppendLine("VPK Information:");
builder.AppendLine("-------------------------");
builder.AppendLine();
PrintHeader(builder);
PrintExtendedHeader(builder);
PrintArchiveHashes(builder);
PrintDirectoryItems(builder);
return builder;
2022-12-24 13:49:03 -08:00
}
/// <summary>
/// Print header information
/// </summary>
2023-01-13 14:04:21 -08:00
/// <param name="builder">StringBuilder to append information to</param>
private void PrintHeader(StringBuilder builder)
2022-12-24 13:49:03 -08:00
{
2023-01-13 14:04:21 -08:00
builder.AppendLine(" Header Information:");
builder.AppendLine(" -------------------------");
builder.AppendLine($" Signature: {Signature} (0x{Signature:X})");
builder.AppendLine($" Version: {Version} (0x{Version:X})");
builder.AppendLine($" Directory length: {DirectoryLength} (0x{DirectoryLength:X})");
builder.AppendLine();
2022-12-24 13:49:03 -08:00
}
/// <summary>
/// Print extended header information
/// </summary>
2023-01-13 14:04:21 -08:00
/// <param name="builder">StringBuilder to append information to</param>
private void PrintExtendedHeader(StringBuilder builder)
2022-12-24 13:49:03 -08:00
{
2023-01-13 14:04:21 -08:00
builder.AppendLine(" Extended Header Information:");
builder.AppendLine(" -------------------------");
2022-12-24 13:49:03 -08:00
if (_file.ExtendedHeader == null)
{
2023-01-13 14:04:21 -08:00
builder.AppendLine(" No extended header");
2022-12-24 13:49:03 -08:00
}
else
{
2023-01-13 14:04:21 -08:00
builder.AppendLine($" Dummy 0: {Dummy0} (0x{Dummy0:X})");
builder.AppendLine($" Archive hash length: {ArchiveHashLength} (0x{ArchiveHashLength:X})");
builder.AppendLine($" Extra length: {ExtraLength} (0x{ExtraLength:X})");
builder.AppendLine($" Dummy 1: {Dummy1} (0x{Dummy1:X})");
builder.AppendLine();
2022-12-24 13:49:03 -08:00
}
}
/// <summary>
/// Print archive hashes information
/// </summary>
2023-01-13 14:04:21 -08:00
/// <param name="builder">StringBuilder to append information to</param>
private void PrintArchiveHashes(StringBuilder builder)
2022-12-24 13:49:03 -08:00
{
2023-01-13 14:04:21 -08:00
builder.AppendLine(" Archive Hashes Information:");
builder.AppendLine(" -------------------------");
2022-12-24 13:49:03 -08:00
if (ArchiveHashes == null || ArchiveHashes.Length == 0)
{
2023-01-13 14:04:21 -08:00
builder.AppendLine(" No archive hashes");
2022-12-24 13:49:03 -08:00
}
else
{
for (int i = 0; i < ArchiveHashes.Length; i++)
{
var archiveHash = ArchiveHashes[i];
2023-01-13 14:04:21 -08:00
builder.AppendLine($" Archive Hash {i}");
builder.AppendLine($" Archive index: {archiveHash.ArchiveIndex} (0x{archiveHash.ArchiveIndex:X})");
builder.AppendLine($" Archive offset: {archiveHash.ArchiveOffset} (0x{archiveHash.ArchiveOffset:X})");
builder.AppendLine($" Length: {archiveHash.Length} (0x{archiveHash.Length:X})");
builder.AppendLine($" Hash: {BitConverter.ToString(archiveHash.Hash).Replace("-", string.Empty)}");
2022-12-24 13:49:03 -08:00
}
}
2023-01-13 14:04:21 -08:00
builder.AppendLine();
2022-12-24 13:49:03 -08:00
}
/// <summary>
/// Print directory items information
/// </summary>
2023-01-13 14:04:21 -08:00
/// <param name="builder">StringBuilder to append information to</param>
private void PrintDirectoryItems(StringBuilder builder)
2022-12-24 13:49:03 -08:00
{
2023-01-13 14:04:21 -08:00
builder.AppendLine(" Directory Items Information:");
builder.AppendLine(" -------------------------");
2022-12-24 13:49:03 -08:00
if (DirectoryItems == null || DirectoryItems.Length == 0)
{
2023-01-13 14:04:21 -08:00
builder.AppendLine(" No directory items");
2022-12-24 13:49:03 -08:00
}
else
{
for (int i = 0; i < DirectoryItems.Length; i++)
{
var directoryItem = DirectoryItems[i];
2023-01-13 14:04:21 -08:00
builder.AppendLine($" Directory Item {i}");
builder.AppendLine($" Extension: {directoryItem.Extension}");
builder.AppendLine($" Path: {directoryItem.Path}");
builder.AppendLine($" Name: {directoryItem.Name}");
PrintDirectoryEntry(directoryItem.DirectoryEntry, builder);
2022-12-24 13:49:03 -08:00
// TODO: Print out preload data?
}
}
2023-01-13 14:04:21 -08:00
builder.AppendLine();
2022-12-24 13:49:03 -08:00
}
/// <summary>
/// Print directory entry information
/// </summary>
2023-01-13 14:04:21 -08:00
/// <param name="builder">StringBuilder to append information to</param>
private void PrintDirectoryEntry(Models.VPK.DirectoryEntry directoryEntry, StringBuilder builder)
2022-12-24 13:49:03 -08:00
{
if (directoryEntry == null)
{
2023-01-13 14:04:21 -08:00
builder.AppendLine(" Directory entry: [NULL]");
2022-12-24 13:49:03 -08:00
}
else
{
2023-01-13 14:04:21 -08:00
builder.AppendLine($" Directory entry CRC: {directoryEntry.CRC} (0x{directoryEntry.CRC:X})");
builder.AppendLine($" Directory entry preload bytes: {directoryEntry.PreloadBytes} (0x{directoryEntry.PreloadBytes:X})");
builder.AppendLine($" Directory entry archive index: {directoryEntry.ArchiveIndex} (0x{directoryEntry.ArchiveIndex:X})");
builder.AppendLine($" Directory entry entry offset: {directoryEntry.EntryOffset} (0x{directoryEntry.EntryOffset:X})");
builder.AppendLine($" Directory entry entry length: {directoryEntry.EntryLength} (0x{directoryEntry.EntryLength:X})");
builder.AppendLine($" Directory entry dummy 0: {directoryEntry.Dummy0} (0x{directoryEntry.Dummy0:X})");
2022-12-24 13:49:03 -08:00
}
}
#if NET6_0_OR_GREATER
/// <inheritdoc/>
public override string ExportJSON() => System.Text.Json.JsonSerializer.Serialize(_file, _jsonSerializerOptions);
#endif
2022-12-24 13:49:03 -08:00
#endregion
#region Extraction
/// <summary>
/// Extract all files from the VPK to an output directory
/// </summary>
/// <param name="outputDirectory">Output directory to write to</param>
/// <returns>True if all files extracted, false otherwise</returns>
public bool ExtractAll(string outputDirectory)
{
// If we have no directory items
if (DirectoryItems == null || DirectoryItems.Length == 0)
return false;
// Loop through and extract all files to the output
bool allExtracted = true;
for (int i = 0; i < DirectoryItems.Length; i++)
{
allExtracted &= ExtractFile(i, outputDirectory);
}
return allExtracted;
}
/// <summary>
/// Extract a file from the VPK to an output directory by index
/// </summary>
/// <param name="index">File index to extract</param>
/// <param name="outputDirectory">Output directory to write to</param>
/// <returns>True if the file extracted, false otherwise</returns>
public bool ExtractFile(int index, string outputDirectory)
{
// If we have no directory items
if (DirectoryItems == null || DirectoryItems.Length == 0)
return false;
// If the directory item index is invalid
if (index < 0 || index >= DirectoryItems.Length)
return false;
// Get the directory item
var directoryItem = DirectoryItems[index];
if (directoryItem?.DirectoryEntry == null)
return false;
2022-12-24 15:25:56 -08:00
// If we have an item with no archive
byte[] data;
2022-12-28 15:27:10 -08:00
if (directoryItem.DirectoryEntry.ArchiveIndex == HL_VPK_NO_ARCHIVE)
2022-12-24 15:25:56 -08:00
{
if (directoryItem.PreloadData == null)
return false;
data = directoryItem.PreloadData;
}
else
{
// If we have invalid archives
if (ArchiveFilenames == null || ArchiveFilenames.Length == 0)
return false;
// If we have an invalid index
if (directoryItem.DirectoryEntry.ArchiveIndex < 0 || directoryItem.DirectoryEntry.ArchiveIndex >= ArchiveFilenames.Length)
return false;
// Get the archive filename
string archiveFileName = ArchiveFilenames[directoryItem.DirectoryEntry.ArchiveIndex];
if (string.IsNullOrWhiteSpace(archiveFileName))
return false;
// If the archive doesn't exist
if (!File.Exists(archiveFileName))
return false;
// Try to open the archive
Stream archiveStream = null;
try
{
// Open the archive
archiveStream = File.OpenRead(archiveFileName);
// Seek to the data
archiveStream.Seek(directoryItem.DirectoryEntry.EntryOffset, SeekOrigin.Begin);
// Read the directory item bytes
data = archiveStream.ReadBytes((int)directoryItem.DirectoryEntry.EntryLength);
}
catch
{
return false;
}
finally
{
archiveStream?.Close();
}
// If we have preload data, prepend it
if (directoryItem.PreloadData != null)
data = directoryItem.PreloadData.Concat(data).ToArray();
}
2022-12-24 13:49:03 -08:00
// Create the filename
string filename = $"{directoryItem.Name}.{directoryItem.Extension}";
2022-12-24 15:25:56 -08:00
if (!string.IsNullOrWhiteSpace(directoryItem.Path))
2022-12-24 13:49:03 -08:00
filename = Path.Combine(directoryItem.Path, filename);
// If we have an invalid output directory
if (string.IsNullOrWhiteSpace(outputDirectory))
return false;
// Create the full output path
filename = Path.Combine(outputDirectory, filename);
2022-12-24 15:25:56 -08:00
// Ensure the output directory is created
Directory.CreateDirectory(Path.GetDirectoryName(filename));
2022-12-24 13:49:03 -08:00
2022-12-24 15:25:56 -08:00
// Try to write the data
try
2022-12-24 13:49:03 -08:00
{
2022-12-24 15:25:56 -08:00
// Open the output file for writing
using (Stream fs = File.OpenWrite(filename))
{
fs.Write(data, 0, data.Length);
}
}
catch
{
return false;
2022-12-24 13:49:03 -08:00
}
return true;
}
#endregion
}
}