Files
GameLauncher/Engines/Nwjs/NwjsPackageUnpacker.cs
T
armonica 8cea2a147d refactor: reorganize engine-based structure and add agent rules
- Engines/ 配下へエンジン別に再編 (Common/Rgss/Tkool/Tyrano/Wolf/Unity/Nwjs)
- ゲーム個別処理を Engines/<Engine>/Games/<GameName>/ へ分離し、共通処理から明示呼び出し
- 外部ツールを Engines/<Engine>/Tools/ へ移動し、AppPathHelper 経由で解決
- 旧 Tools/ 直下参照と不要な参照ファイル/バックアップを削除
- エージェント規則 AGENTS.md を追加し、README から参照
- publish.ps1 を Engines/<Engine>/Tools/ の再帰配置に対応
2026-10-07 02:30:49 +09:00

379 lines
16 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Security.Cryptography;
namespace GameLauncher.Engines.Nwjs
{
/// <summary>
/// nw.js 系(boxed / FOSSIL 等の単体exe梱包)ツクールゲームから、
/// 埋め込まれた package.nw 相当のコンテナを抽出する汎用アンパッカー。
///
/// 方針(恒久・再利用可能):
/// - 特定ゲーム専用ではなく、共通の署名探索アルゴリズムで「埋め込みZIPコンテナ」を探す。
/// - exe 全体を一括読みしない。ブロック単位の逐次走査で PK ローカルヘッダ→EOCD を確定する。
/// - 抽出先はゲームフォルダ内 `_extracted` のみ(他ゲームへ一切影響しない)。
/// - 冪等: 既に展開済み(plugins.js が解決できる)なら再展開しない。
///
/// 抽出戦略は <see cref="INwjsUnpackStrategy"/> として差し替え可能にしてあり、
/// 将来新しい梱包形式が出た場合は戦略を追加するだけで拡張できる。
/// </summary>
public static class NwjsPackageUnpacker
{
/// <summary>ゲームフォルダ内の展開先フォルダ名(Asar/SRPG の慣習に合わせる)</summary>
public const string ExtractedDirName = "_extracted";
/// <summary>走査ブロックサイズ(1ブロックあたりの読み込み量)</summary>
private const int ScanBlockSize = 4 * 1024 * 1024;
/// <summary>単一のPKローカルヘッダから読み込める最大ウィンドウ(EOCD 探索用)</summary>
private const int MaxSingleZipScan = 256 * 1024 * 1024;
/// <summary>ゲームフォルダ内の展開先ディレクトリ(物理パス)</summary>
public static string GetExtractedDir(string gameRootDir)
=> Path.Combine(gameRootDir, ExtractedDirName);
/// <summary>
/// 展開先 `_extracted` に js/plugins.js(または www/js/plugins.js)が存在するか判定します。
/// </summary>
public static bool IsExtractionComplete(string extractedDir, out string? pluginsJsPath, out string? relativePlugins)
{
pluginsJsPath = null;
relativePlugins = null;
try
{
var candidates = new[]
{
new { Abs = Path.Combine(extractedDir, "js", "plugins.js"), Rel = "js/plugins.js" },
new { Abs = Path.Combine(extractedDir, "js", "plugins", "plugins.js"), Rel = "js/plugins/plugins.js" },
new { Abs = Path.Combine(extractedDir, "www", "js", "plugins.js"), Rel = "www/js/plugins.js" },
};
foreach (var c in candidates)
{
if (File.Exists(c.Abs))
{
pluginsJsPath = c.Abs;
relativePlugins = c.Rel;
return true;
}
}
}
catch { }
return false;
}
/// <summary>
/// 指定パス直下から js/plugins.js を解決します(_extracted 配下優先)。
/// </summary>
public static string? ResolvePluginsJs(string rootDir)
{
try
{
var candidates = new[]
{
Path.Combine(rootDir, "js", "plugins.js"),
Path.Combine(rootDir, "js", "plugins", "plugins.js"),
Path.Combine(rootDir, "www", "js", "plugins.js"),
Path.Combine(rootDir, "package.nw", "js", "plugins.js"),
};
return candidates.FirstOrDefault(File.Exists);
}
catch
{
return null;
}
}
/// <summary>
/// 判定に必要な署名情報。汎用の埋め込みZIPコンテナ有無を表します。
/// </summary>
public sealed class EmbeddedZipProbeResult
{
/// <summary>PK ローカルヘッダ(PK\x03\x04)の先頭オフセット(見つかった場合)</summary>
public long? LocalHeaderOffset { get; init; }
/// <summary>EOCD(PK\x05\x06)の末尾オフセット(見つかった場合)</summary>
public long? EocdOffset { get; init; }
/// <summary>コンテナ内に package.json 文字列が見つかったか</summary>
public bool HasPackageJson { get; init; }
/// <summary>標準ZIPとして展開可能そうか</summary>
public bool IsZipExtractable => LocalHeaderOffset.HasValue && EocdOffset.HasValue;
}
/// <summary>
/// 埋め込みコンテナ(package.nw = 標準ZIP)を逐次走査で探索します。全走査でも
/// exe を一括メモリへ載せないため、1.14GB級でも安全です。
/// </summary>
/// <param name="exePath">対象の単体exeパス</param>
/// <param name="progress">進捗通知(任意)</param>
/// <param name="maxScanBytes">先頭から走査する最大バイト数(既定は末尾まで)</param>
public static EmbeddedZipProbeResult ProbeEmbeddedZip(string exePath, IProgress<string>? progress = null, long maxScanBytes = long.MaxValue)
{
if (!File.Exists(exePath))
{
return new EmbeddedZipProbeResult();
}
long? localHeader = null;
bool hasPackageJson = false;
using var fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
long fileSize = fs.Length;
long scanLimit = Math.Min(fileSize, maxScanBytes);
var buf = new byte[ScanBlockSize];
long pos = 0;
// ブロック境界をまたぐPK検出のため、直前3バイトを保持する
int carry = 0;
byte b1 = 0, b2 = 0, b3 = 0;
progress?.Report($"埋め込みZIPコンテナを走査中... ({fileSize:N0} bytes)");
while (pos < scanLimit)
{
int toRead = (int)Math.Min(buf.Length, scanLimit - pos);
fs.Seek(pos, SeekOrigin.Begin);
int read = fs.Read(buf, 0, toRead);
if (read <= 0)
{
break;
}
for (int i = 0; i < read; i++)
{
byte cur = buf[i];
if (carry == 3 && b1 == 0x50 && b2 == 0x4B && b3 == 0x03 && cur == 0x04 && localHeader == null)
{
// ローカルヘッダ先頭位置 = (今回ブロック開始 - 3) + (i - 3)
long abs = pos + i - 3;
if (abs >= 0)
{
localHeader = abs;
progress?.Report($"埋め込みZIPローカルヘッダを検出: offset={abs:N0}");
}
}
if (b1 == 0x50 && b2 == 0x4B && b3 == 0x03 && cur == 0x04)
{
b1 = b2; b2 = b3; b3 = cur;
}
else
{
b1 = b2; b2 = b3; b3 = cur;
}
if (carry < 3)
{
carry++;
}
}
// ブロック内で package.json 文字列を軽く探索(タイトル推定用・厳密性は不要)
if (!hasPackageJson)
{
var ascii = System.Text.Encoding.ASCII.GetString(buf, 0, read);
if (ascii.IndexOf("package.json", StringComparison.Ordinal) >= 0)
{
hasPackageJson = true;
}
}
pos += read;
progress?.Report($"走査中... {pos:N0} / {fileSize:N0} bytes");
}
// EOCD(PK\x05\x06)は末尾近傍にある。末尾 64KB を走査。
long? eocd = null;
if (localHeader.HasValue)
{
int tailLen = (int)Math.Min(64 * 1024, fileSize);
var tail = new byte[tailLen];
fs.Seek(fileSize - tailLen, SeekOrigin.Begin);
int tr = fs.Read(tail, 0, tailLen);
for (int i = tr - 4; i >= 0; i--)
{
if (tail[i] == 0x50 && tail[i + 1] == 0x4B && tail[i + 2] == 0x05 && tail[i + 3] == 0x06)
{
eocd = (fileSize - tailLen) + i;
break;
}
}
// 末尾64KBに無ければローカルヘッダ以降の限定ウィンドウも確認(巨大な付加データ対策)
if (eocd == null)
{
eocd = FindEocdNearOffset(fs, localHeader.Value, fileSize);
}
}
return new EmbeddedZipProbeResult
{
LocalHeaderOffset = localHeader,
EocdOffset = eocd,
HasPackageJson = hasPackageJson
};
}
/// <summary>
/// ローカルヘッダ以降を(最大<see cref="MaxSingleZipScan"/>まで)限定走査し、EOCD 位置を探します。
/// </summary>
private static long? FindEocdNearOffset(FileStream fs, long start, long fileSize)
{
long limit = Math.Min(fileSize, start + MaxSingleZipScan);
// 末尾から逆方向に少しずつ探す方が現実的だが、境界が読めない場合は後方優先で探す
long window = 4 * 1024 * 1024;
for (long end = limit; end > start; end -= window)
{
long begin = Math.Max(start, end - window);
int len = (int)(end - begin);
if (len <= 4)
{
continue;
}
var buf = new byte[len];
fs.Seek(begin, SeekOrigin.Begin);
int read = fs.Read(buf, 0, len);
for (int i = read - 4; i >= 0; i--)
{
if (buf[i] == 0x50 && buf[i + 1] == 0x4B && buf[i + 2] == 0x05 && buf[i + 3] == 0x06)
{
return begin + i;
}
}
}
return null;
}
/// <summary>
/// exe 内に埋め込まれた ZIP(package.nw)を、指定の展開先へ冪等に全展開します。
/// 標準ZIPとして解釈できる場合のみ成功します。
/// </summary>
/// <returns>展開後の js/plugins.js の相対パス(/区切り)。解決できなければ null。</returns>
public static string? ExtractEmbeddedZip(string exePath, string destDir, IProgress<string>? progress = null)
{
try
{
var probe = ProbeEmbeddedZip(exePath, progress);
if (!probe.IsZipExtractable)
{
progress?.Report("埋め込みZIPコンテナを確定できませんでした(非標準コンテナの可能性)。");
return null;
}
Directory.CreateDirectory(destDir);
using var fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
long zipLength = probe.EocdOffset!.Value + 22 - probe.LocalHeaderOffset!.Value;
fs.Seek(probe.LocalHeaderOffset!.Value, SeekOrigin.Begin);
// EOCD を含む範囲だけを ZipArchive へ渡す(exe 末尾の付加データを切り離す)
using var slice = new SubStream(fs, probe.LocalHeaderOffset!.Value, zipLength);
using var zip = new ZipArchive(slice, ZipArchiveMode.Read);
foreach (var entry in zip.Entries)
{
var entryRel = entry.FullName.Replace('/', Path.DirectorySeparatorChar);
var dest = Path.Combine(destDir, entryRel);
// ディレクトリエントリ
if (string.IsNullOrEmpty(entry.Name))
{
Directory.CreateDirectory(dest);
continue;
}
var parent = Path.GetDirectoryName(dest);
if (!string.IsNullOrEmpty(parent))
{
Directory.CreateDirectory(parent);
}
using (var src = entry.Open())
using (var outFs = new FileStream(dest, FileMode.Create, FileAccess.Write, FileShare.None))
{
src.CopyTo(outFs);
}
}
progress?.Report("埋め込みZIPコンテナの展開が完了しました。");
return IsExtractionComplete(destDir, out _, out var rel) ? rel : null;
}
catch (Exception ex)
{
progress?.Report($"埋め込みZIP展開中にエラーが発生しました: {ex.Message}");
return null;
}
}
/// <summary>
/// 指定範囲のみを読み出す読み取り専用ストリーム(ZIP末尾の付加データ分離用)。
/// </summary>
private sealed class SubStream : Stream
{
private readonly Stream _base;
private readonly long _start;
private readonly long _length;
private long _pos;
public SubStream(Stream baseStream, long start, long length)
{
_base = baseStream;
_start = start;
_length = length;
}
public override bool CanRead => true;
public override bool CanSeek => true;
public override bool CanWrite => false;
public override long Length => _length;
public override long Position
{
get => _pos;
set => _pos = value;
}
public override int Read(byte[] buffer, int offset, int count)
{
long remaining = _length - _pos;
if (remaining <= 0)
{
return 0;
}
int toRead = (int)Math.Min(count, remaining);
_base.Seek(_start + _pos, SeekOrigin.Begin);
int read = _base.Read(buffer, offset, toRead);
_pos += read;
return read;
}
public override long Seek(long offset, SeekOrigin origin)
{
_pos = origin switch
{
SeekOrigin.Begin => offset,
SeekOrigin.Current => _pos + offset,
SeekOrigin.End => _length + offset,
_ => _pos
};
return _pos;
}
public override void Flush() { }
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
}
/// <summary>
/// 抽出戦略の抽象。標準ZIP以外の独自コンテナが出た場合に差し替え可能にするための骨組み。
/// </summary>
public interface INwjsUnpackStrategy
{
string Name { get; }
bool CanHandle(string exePath);
string? Extract(string exePath, string destDir, IProgress<string>? progress);
}
}
}