Decompiled source of MEM TetoAndPearto Fix v1.0.0

plugins/TetoEyesFix.dll

Decompiled 14 hours ago
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace TetoEyesFix;

[BepInPlugin("local.repo.tetoaddon.eyesfix", "Teto Eyes Fix", "1.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class TetoEyesFixPlugin : BaseUnityPlugin
{
	public const string PluginGuid = "local.repo.tetoaddon.eyesfix";

	public const string TargetGuid = "local.repo.tetoaddon";

	private const string PatchResource = "teto.rpm.eyesfix";

	internal static ManualLogSource Log;

	private static byte[] patchData;

	private static ConfigEntry<bool> skipBaseHashCheck;

	private void Awake()
	{
		Log = ((BaseUnityPlugin)this).Logger;
		skipBaseHashCheck = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "SkipBaseModHashCheck", true, "Teto & Pearto 0.3.2 refuses to load unless UmamusumeSemibots is byte-identical to version 2.2.0. Keep this true if your UmamusumeSemibots build differs (e.g. a newer 2.2.x). Set false for the original strict behaviour.");
		try
		{
			if (!Chainloader.PluginInfos.TryGetValue("local.repo.tetoaddon", out var value) || value.Instance == null)
			{
				Log.LogError((object)"Teto & Pearto (local.repo.tetoaddon) is not loaded; nothing to fix.");
				return;
			}
			Assembly assembly = ((object)value.Instance).GetType().Assembly;
			Log.LogInfo((object)string.Concat("Found Teto & Pearto ", value.Metadata.Version, " at ", assembly.Location));
			int num = Install(assembly, skipBaseHashCheck.Value);
			Log.LogInfo((object)("Teto Eyes Fix ready (" + num + " patch(es) applied)."));
		}
		catch (Exception ex)
		{
			Log.LogError((object)("Teto Eyes Fix failed to initialise; the original mod is left untouched: " + ex));
		}
	}

	internal static int Install(Assembly asm, bool skipHashCheck)
	{
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Expected O, but got Unknown
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Expected O, but got Unknown
		//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cb: Expected O, but got Unknown
		patchData = LoadEmbeddedPatch();
		Harmony val = new Harmony("local.repo.tetoaddon.eyesfix");
		int num = 0;
		Type type = asm.GetType("RepoTeto.RuntimeModelFactory", throwOnError: true);
		MethodInfo methodInfo = AccessTools.Method(type, "CreateTeto", (Type[])null, (Type[])null);
		if (methodInfo == null)
		{
			throw new MissingMethodException("RuntimeModelFactory.CreateTeto");
		}
		val.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(TetoEyesFixPlugin), "CreateTetoTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
		num++;
		if (skipHashCheck)
		{
			Type type2 = asm.GetType("RepoTeto.TetoAddon", throwOnError: true);
			MethodInfo methodInfo2 = AccessTools.Method(type2, "RegisterModel", (Type[])null, (Type[])null);
			if (methodInfo2 == null)
			{
				throw new MissingMethodException("TetoAddon.RegisterModel");
			}
			val.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(TetoEyesFixPlugin), "RegisterModelTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
			num++;
		}
		return num;
	}

	public static IEnumerable<CodeInstruction> CreateTetoTranspiler(IEnumerable<CodeInstruction> instructions)
	{
		MethodInfo replacement = AccessTools.Method(typeof(TetoEyesFixPlugin), "OpenTeto", (Type[])null, (Type[])null);
		MethodInfo openRead = AccessTools.Method(typeof(File), "OpenRead", new Type[1] { typeof(string) }, (Type[])null);
		int replaced = 0;
		foreach (CodeInstruction ci in instructions)
		{
			if (replaced == 0 && ci.opcode == OpCodes.Call && ci.operand as MethodInfo == openRead)
			{
				ci.operand = replacement;
				replaced++;
			}
			yield return ci;
		}
		if (replaced == 0)
		{
			Log.LogError((object)"CreateTeto: File.OpenRead call not found - eye fix NOT applied (incompatible Teto & Pearto version?).");
		}
	}

	public static IEnumerable<CodeInstruction> RegisterModelTranspiler(IEnumerable<CodeInstruction> instructions)
	{
		List<CodeInstruction> list = new List<CodeInstruction>(instructions);
		bool flag = false;
		for (int i = 0; i + 2 < list.Count; i++)
		{
			string text = list[i].operand as string;
			if (list[i].opcode == OpCodes.Ldstr && text != null && text.IndexOf("inspected UmamusumeSemibots", StringComparison.Ordinal) >= 0 && list[i + 1].opcode == OpCodes.Newobj && list[i + 2].opcode == OpCodes.Throw)
			{
				for (int j = 0; j < 3; j++)
				{
					list[i + j].opcode = OpCodes.Nop;
					list[i + j].operand = null;
				}
				flag = true;
				break;
			}
		}
		if (!flag)
		{
			Log.LogWarning((object)"RegisterModel: base-mod hash check not found - nothing to skip.");
		}
		return list;
	}

	public static Stream OpenTeto(string path)
	{
		try
		{
			if (!string.Equals(Path.GetFileName(path), "teto.rpm", StringComparison.OrdinalIgnoreCase))
			{
				return File.OpenRead(path);
			}
			byte[] data = File.ReadAllBytes(path);
			byte[] buffer = ApplyPatch(data);
			return new MemoryStream(buffer, writable: false);
		}
		catch (Exception ex)
		{
			Log.LogError((object)("Eye fix failed, loading teto.rpm unmodified: " + ex.Message));
			return File.OpenRead(path);
		}
	}

	private static byte[] ApplyPatch(byte[] data)
	{
		using BinaryReader binaryReader = new BinaryReader(new MemoryStream(patchData));
		if (Encoding.ASCII.GetString(binaryReader.ReadBytes(8)) != "ETFIX001")
		{
			throw new InvalidDataException("Bad patch header.");
		}
		byte[] b = binaryReader.ReadBytes(32);
		byte[] b2 = binaryReader.ReadBytes(32);
		int num = (int)binaryReader.ReadUInt32();
		byte[] array = Sha256(data);
		if (Equal(array, b2))
		{
			Log.LogInfo((object)"teto.rpm already contains the eye fix; leaving as is.");
			return data;
		}
		if (!Equal(array, b))
		{
			Log.LogWarning((object)("teto.rpm is not the expected Teto & Pearto 0.3.2 file (SHA-256 " + Hex(array) + "). Eye fix NOT applied."));
			return data;
		}
		byte[] array2 = (byte[])data.Clone();
		for (int i = 0; i < num; i++)
		{
			int num2 = (int)binaryReader.ReadUInt32();
			int num3 = (int)binaryReader.ReadUInt32();
			byte[] array3 = binaryReader.ReadBytes(num3);
			if (array3.Length != num3 || num2 < 0 || num2 + num3 > array2.Length)
			{
				throw new InvalidDataException("Corrupt patch.");
			}
			Buffer.BlockCopy(array3, 0, array2, num2, num3);
		}
		if (!Equal(Sha256(array2), b2))
		{
			throw new InvalidDataException("Patched teto.rpm failed verification.");
		}
		Log.LogInfo((object)("Eye fix applied to teto.rpm in memory (" + num + " edits). No files were changed."));
		return array2;
	}

	private static byte[] LoadEmbeddedPatch()
	{
		using Stream stream = typeof(TetoEyesFixPlugin).Assembly.GetManifestResourceStream("teto.rpm.eyesfix");
		if (stream == null)
		{
			throw new FileNotFoundException("Embedded resource missing: teto.rpm.eyesfix");
		}
		using MemoryStream memoryStream = new MemoryStream();
		byte[] array = new byte[8192];
		int count;
		while ((count = stream.Read(array, 0, array.Length)) > 0)
		{
			memoryStream.Write(array, 0, count);
		}
		return memoryStream.ToArray();
	}

	private static byte[] Sha256(byte[] b)
	{
		using SHA256 sHA = SHA256.Create();
		return sHA.ComputeHash(b);
	}

	private static string Hex(byte[] b)
	{
		return BitConverter.ToString(b).Replace("-", string.Empty).ToLowerInvariant();
	}

	private static bool Equal(byte[] a, byte[] b)
	{
		if (a.Length != b.Length)
		{
			return false;
		}
		for (int i = 0; i < a.Length; i++)
		{
			if (a[i] != b[i])
			{
				return false;
			}
		}
		return true;
	}
}