You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

440 lines
16 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Runtime.InteropServices;
  9. using System.Text.RegularExpressions;
  10. using System.Windows.Forms;
  11. using IPA.Patcher;
  12. namespace IPA
  13. {
  14. [SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
  15. public static class Program
  16. {
  17. [SuppressMessage("ReSharper", "InconsistentNaming")]
  18. public enum Architecture
  19. {
  20. x86,
  21. x64,
  22. Unknown
  23. }
  24. public const string FileVersion = "3.99.99.10";
  25. public static Version Version => Assembly.GetEntryAssembly().GetName().Version;
  26. public static readonly ArgumentFlag ArgHelp = new ArgumentFlag("--help", "-h") { DocString = "prints this message" };
  27. public static readonly ArgumentFlag ArgWaitFor = new ArgumentFlag("--waitfor", "-w") { DocString = "waits for the specified PID to exit", ValueString = "PID" };
  28. public static readonly ArgumentFlag ArgForce = new ArgumentFlag("--force", "-f") { DocString = "forces the operation to go through" };
  29. public static readonly ArgumentFlag ArgRevert = new ArgumentFlag("--revert", "-r") { DocString = "reverts the IPA installation" };
  30. public static readonly ArgumentFlag ArgNoRevert = new ArgumentFlag("--no-revert", "-R") { DocString = "prevents a normal installation from first reverting" };
  31. public static readonly ArgumentFlag ArgNoWait = new ArgumentFlag("--nowait", "-n") { DocString = "doesn't wait for user input after the operation" };
  32. public static readonly ArgumentFlag ArgStart = new ArgumentFlag("--start", "-s") { DocString = "uses the specified arguments to start the game after the patch/unpatch", ValueString = "ARGUMENTS" };
  33. public static readonly ArgumentFlag ArgLaunch = new ArgumentFlag("--launch", "-l") { DocString = "uses positional parameters as arguments to start the game after patch/unpatch" };
  34. [STAThread]
  35. public static void Main()
  36. {
  37. Arguments.CmdLine.Flags(ArgHelp, ArgWaitFor, ArgForce, ArgRevert, ArgNoWait, ArgStart, ArgLaunch, ArgNoRevert).Process();
  38. if (ArgHelp)
  39. {
  40. Arguments.CmdLine.PrintHelp();
  41. return;
  42. }
  43. try
  44. {
  45. if (ArgWaitFor.HasValue)
  46. { // wait for process if necessary
  47. var pid = int.Parse(ArgWaitFor.Value);
  48. try
  49. { // wait for beat saber to exit (ensures we can modify the file)
  50. var parent = Process.GetProcessById(pid);
  51. Console.WriteLine($"Waiting for parent ({pid}) process to die...");
  52. parent.WaitForExit();
  53. }
  54. catch (Exception)
  55. {
  56. // ignored
  57. }
  58. }
  59. PatchContext context = null;
  60. Assembly AssemblyLibLoader(object source, ResolveEventArgs e)
  61. {
  62. // ReSharper disable AccessToModifiedClosure
  63. if (context == null) return null;
  64. var libsDir = context.LibsPathSrc;
  65. // ReSharper enable AccessToModifiedClosure
  66. var asmName = new AssemblyName(e.Name);
  67. var testFile = Path.Combine(libsDir, $"{asmName.Name}.{asmName.Version}.dll");
  68. if (File.Exists(testFile))
  69. return Assembly.LoadFile(testFile);
  70. Console.WriteLine($"Could not load library {asmName}");
  71. return null;
  72. }
  73. AppDomain.CurrentDomain.AssemblyResolve += AssemblyLibLoader;
  74. var argExeName = Arguments.CmdLine.PositionalArgs.FirstOrDefault(s => s.EndsWith(".exe"));
  75. if (argExeName == null)
  76. context = PatchContext.Create(new DirectoryInfo(Directory.GetCurrentDirectory()).GetFiles()
  77. .First(o => o.Extension == ".exe" && o.FullName != Assembly.GetEntryAssembly().Location)
  78. .FullName);
  79. else
  80. context = PatchContext.Create(argExeName);
  81. // Sanitizing
  82. Validate(context);
  83. if (ArgRevert || Keyboard.IsKeyDown(Keys.LMenu))
  84. Revert(context);
  85. else
  86. {
  87. Install(context);
  88. StartIfNeedBe(context);
  89. }
  90. }
  91. catch (Exception e)
  92. {
  93. Fail(e.Message);
  94. }
  95. WaitForEnd();
  96. }
  97. private static void WaitForEnd()
  98. {
  99. if (!ArgNoWait)
  100. {
  101. Console.ForegroundColor = ConsoleColor.DarkYellow;
  102. Console.WriteLine("[Press any key to continue]");
  103. Console.ResetColor();
  104. Console.ReadKey();
  105. }
  106. }
  107. private static void Validate(PatchContext c)
  108. {
  109. if (!Directory.Exists(c.DataPathDst) || !File.Exists(c.EngineFile))
  110. {
  111. Fail("Game does not seem to be a Unity project. Could not find the libraries to patch.");
  112. Console.WriteLine($"DataPath: {c.DataPathDst}");
  113. Console.WriteLine($"EngineFile: {c.EngineFile}");
  114. }
  115. }
  116. private static void Install(PatchContext context)
  117. {
  118. try
  119. {
  120. bool installFiles = true;
  121. // first, check currently installed version, if any
  122. if (File.Exists(Path.Combine(context.ProjectRoot, "winhttp.dll")))
  123. { // installed, so check version of installed assembly
  124. string injectorPath = Path.Combine(context.ManagedPath, "IPA.Injector.dll");
  125. if (File.Exists(injectorPath))
  126. {
  127. var verInfo = FileVersionInfo.GetVersionInfo(injectorPath);
  128. var fileVersion = new Version(verInfo.FileVersion);
  129. if (fileVersion > Version)
  130. installFiles = false;
  131. }
  132. }
  133. if (installFiles || ArgForce)
  134. {
  135. var backup = new BackupUnit(context);
  136. if (!ArgNoRevert)
  137. {
  138. Console.ForegroundColor = ConsoleColor.Cyan;
  139. Console.WriteLine("Restoring old version... ");
  140. if (BackupManager.HasBackup(context))
  141. BackupManager.Restore(context);
  142. }
  143. var nativePluginFolder = Path.Combine(context.DataPathDst, "Plugins");
  144. bool isFlat = Directory.Exists(nativePluginFolder) &&
  145. Directory.GetFiles(nativePluginFolder).Any(f => f.EndsWith(".dll"));
  146. bool force = !BackupManager.HasBackup(context) || ArgForce;
  147. var architecture = DetectArchitecture(context.Executable);
  148. Console.ForegroundColor = ConsoleColor.DarkCyan;
  149. Console.WriteLine("Installing files... ");
  150. CopyAll(new DirectoryInfo(context.DataPathSrc), new DirectoryInfo(context.DataPathDst), force,
  151. backup);
  152. CopyAll(new DirectoryInfo(context.LibsPathSrc), new DirectoryInfo(context.LibsPathDst), force,
  153. backup);
  154. CopyAll(new DirectoryInfo(context.IPARoot), new DirectoryInfo(context.ProjectRoot), force,
  155. backup,
  156. null, false);
  157. }
  158. else
  159. {
  160. Console.ForegroundColor = ConsoleColor.Yellow;
  161. Console.WriteLine("Not copying files because newer version already installed");
  162. }
  163. #region Create Plugin Folder
  164. if (!Directory.Exists(context.PluginsFolder))
  165. {
  166. Console.ForegroundColor = ConsoleColor.DarkYellow;
  167. Console.WriteLine("Creating plugins folder... ");
  168. Directory.CreateDirectory(context.PluginsFolder);
  169. Console.ResetColor();
  170. }
  171. #endregion
  172. }
  173. catch (Exception e)
  174. {
  175. Console.ForegroundColor = ConsoleColor.Red;
  176. Fail("Oops! This should not have happened.\n\n" + e);
  177. }
  178. Console.ResetColor();
  179. }
  180. private static void Revert(PatchContext context)
  181. {
  182. Console.ForegroundColor = ConsoleColor.Cyan;
  183. Console.Write("Restoring backup... ");
  184. if (BackupManager.Restore(context))
  185. {
  186. Console.WriteLine("Done!");
  187. }
  188. else
  189. {
  190. Console.WriteLine("Already vanilla or you removed your backups!");
  191. }
  192. if (File.Exists(context.ShortcutPath))
  193. {
  194. Console.WriteLine("Deleting shortcut...");
  195. File.Delete(context.ShortcutPath);
  196. }
  197. Console.WriteLine("");
  198. Console.WriteLine("--- Done reverting ---");
  199. Console.ResetColor();
  200. }
  201. private static void StartIfNeedBe(PatchContext context)
  202. {
  203. if (ArgStart.HasValue)
  204. {
  205. Process.Start(context.Executable, ArgStart.Value);
  206. }
  207. else
  208. {
  209. var argList = Arguments.CmdLine.PositionalArgs.ToList();
  210. argList.Remove(context.Executable);
  211. if (ArgLaunch)
  212. {
  213. Process.Start(context.Executable, Args(argList.ToArray()));
  214. }
  215. }
  216. }
  217. public static void ClearLine()
  218. {
  219. if (IsConsole)
  220. {
  221. Console.SetCursorPosition(0, Console.CursorTop);
  222. int tpos = Console.CursorTop;
  223. Console.Write(new string(' ', Console.WindowWidth));
  224. Console.SetCursorPosition(0, tpos);
  225. }
  226. }
  227. private static IEnumerable<FileInfo> PassThroughInterceptor(FileInfo from, FileInfo to)
  228. {
  229. yield return to;
  230. }
  231. public static void CopyAll(DirectoryInfo source, DirectoryInfo target, bool aggressive, BackupUnit backup,
  232. Func<FileInfo, FileInfo, IEnumerable<FileInfo>> interceptor = null, bool recurse = true)
  233. {
  234. if (interceptor == null)
  235. {
  236. interceptor = PassThroughInterceptor;
  237. }
  238. // Copy each file into the new directory.
  239. foreach (var fi in source.GetFiles())
  240. {
  241. foreach (var targetFile in interceptor(fi, new FileInfo(Path.Combine(target.FullName, fi.Name))))
  242. {
  243. if (targetFile.Exists && targetFile.LastWriteTimeUtc >= fi.LastWriteTimeUtc && !aggressive)
  244. continue;
  245. Debug.Assert(targetFile.Directory != null, "targetFile.Directory != null");
  246. targetFile.Directory?.Create();
  247. LineBack();
  248. ClearLine();
  249. Console.WriteLine(@"Copying {0}", targetFile.FullName);
  250. backup.Add(targetFile);
  251. fi.CopyTo(targetFile.FullName, true);
  252. }
  253. }
  254. // Copy each subdirectory using recursion.
  255. if (!recurse) return;
  256. foreach (var diSourceSubDir in source.GetDirectories())
  257. {
  258. var nextTargetSubDir = new DirectoryInfo(Path.Combine(target.FullName, diSourceSubDir.Name));
  259. CopyAll(diSourceSubDir, nextTargetSubDir, aggressive, backup, interceptor);
  260. }
  261. }
  262. private static void Fail(string message)
  263. {
  264. Console.Error.WriteLine("ERROR: " + message);
  265. WaitForEnd();
  266. Environment.Exit(1);
  267. }
  268. public static string Args(params string[] args)
  269. {
  270. return string.Join(" ", args.Select(EncodeParameterArgument).ToArray());
  271. }
  272. /// <summary>
  273. /// Encodes an argument for passing into a program
  274. /// </summary>
  275. /// <param name="original">The value_ that should be received by the program</param>
  276. /// <returns>The value_ which needs to be passed to the program for the original value_
  277. /// to come through</returns>
  278. public static string EncodeParameterArgument(string original)
  279. {
  280. if (string.IsNullOrEmpty(original))
  281. return original;
  282. string value = Regex.Replace(original, @"(\\*)" + "\"", @"$1\$0");
  283. value = Regex.Replace(value, @"^(.*\s.*?)(\\*)$", "\"$1$2$2\"");
  284. return value;
  285. }
  286. public static Architecture DetectArchitecture(string assembly)
  287. {
  288. using (var reader = new BinaryReader(File.OpenRead(assembly)))
  289. {
  290. var header = reader.ReadUInt16();
  291. if (header == 0x5a4d)
  292. {
  293. reader.BaseStream.Seek(60, SeekOrigin.Begin); // this location contains the offset for the PE header
  294. var peOffset = reader.ReadUInt32();
  295. reader.BaseStream.Seek(peOffset + 4, SeekOrigin.Begin);
  296. var machine = reader.ReadUInt16();
  297. if (machine == 0x8664) // IMAGE_FILE_MACHINE_AMD64
  298. return Architecture.x64;
  299. if (machine == 0x014c) // IMAGE_FILE_MACHINE_I386
  300. return Architecture.x86;
  301. if (machine == 0x0200) // IMAGE_FILE_MACHINE_IA64
  302. return Architecture.x64;
  303. return Architecture.Unknown;
  304. }
  305. // Not a supported binary
  306. return Architecture.Unknown;
  307. }
  308. }
  309. public static void ResetLine()
  310. {
  311. if (IsConsole)
  312. Console.CursorLeft = 0;
  313. else
  314. Console.Write("\r");
  315. }
  316. public static void LineBack()
  317. {
  318. if (IsConsole)
  319. Console.CursorTop--;
  320. else
  321. Console.Write("\x1b[1A");
  322. }
  323. [DllImport("kernel32.dll")]
  324. private static extern IntPtr GetConsoleWindow();
  325. private static bool? isConsole;
  326. public static bool IsConsole
  327. {
  328. get
  329. {
  330. if (isConsole == null)
  331. isConsole = GetConsoleWindow() != IntPtr.Zero;
  332. return isConsole.Value;
  333. }
  334. }
  335. internal static class Keyboard
  336. {
  337. [Flags]
  338. private enum KeyStates
  339. {
  340. None = 0,
  341. Down = 1,
  342. Toggled = 2
  343. }
  344. [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
  345. private static extern short GetKeyState(int keyCode);
  346. private static KeyStates KeyState(Keys key)
  347. {
  348. KeyStates state = KeyStates.None;
  349. short retVal = GetKeyState((int)key);
  350. //If the high-order bit is 1, the key is down
  351. //otherwise, it is up.
  352. if ((retVal & 0x8000) == 0x8000)
  353. state |= KeyStates.Down;
  354. //If the low-order bit is 1, the key is toggled.
  355. if ((retVal & 1) == 1)
  356. state |= KeyStates.Toggled;
  357. return state;
  358. }
  359. public static bool IsKeyDown(Keys key)
  360. {
  361. return KeyStates.Down == (KeyState(key) & KeyStates.Down);
  362. }
  363. public static bool IsKeyToggled(Keys key)
  364. {
  365. return KeyStates.Toggled == (KeyState(key) & KeyStates.Toggled);
  366. }
  367. }
  368. }
  369. }