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.

486 lines
18 KiB

5 years ago
6 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 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.13.4";
  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 ArgNoWait = new ArgumentFlag("--nowait", "-n") { DocString = "doesn't wait for user input after the operation" };
  31. public static readonly ArgumentFlag ArgStart = new ArgumentFlag("--start", "-s") { DocString = "uses value_ as arguments to start the game after the patch/unpatch", ValueString = "ARGUMENTS" };
  32. public static readonly ArgumentFlag ArgLaunch = new ArgumentFlag("--launch", "-l") { DocString = "uses positional parameters as arguments to start the game after patch/unpatch" };
  33. //public static readonly ArgumentFlag ArgDestructive = new ArgumentFlag("--destructive", "-d") { DocString = "patches the game using the now outdated destructive methods" };
  34. [STAThread]
  35. public static void Main(string[] args)
  36. {
  37. Arguments.CmdLine.Flags(ArgHelp, ArgWaitFor, ArgForce, ArgRevert, ArgNoWait, ArgStart, ArgLaunch/*, ArgDestructive*/).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. Console.ForegroundColor = ConsoleColor.Cyan;
  137. Console.WriteLine("Restoring old version... ");
  138. if (BackupManager.HasBackup(context))
  139. BackupManager.Restore(context);
  140. var nativePluginFolder = Path.Combine(context.DataPathDst, "Plugins");
  141. bool isFlat = Directory.Exists(nativePluginFolder) &&
  142. Directory.GetFiles(nativePluginFolder).Any(f => f.EndsWith(".dll"));
  143. bool force = !BackupManager.HasBackup(context) || ArgForce;
  144. var architecture = DetectArchitecture(context.Executable);
  145. Console.ForegroundColor = ConsoleColor.DarkCyan;
  146. Console.WriteLine("Installing files... ");
  147. CopyAll(new DirectoryInfo(context.DataPathSrc), new DirectoryInfo(context.DataPathDst), force,
  148. backup,
  149. (from, to) => NativePluginInterceptor(from, to, new DirectoryInfo(nativePluginFolder), isFlat,
  150. architecture));
  151. CopyAll(new DirectoryInfo(context.LibsPathSrc), new DirectoryInfo(context.LibsPathDst), force,
  152. backup,
  153. (from, to) => NativePluginInterceptor(from, to, new DirectoryInfo(nativePluginFolder), isFlat,
  154. architecture));
  155. CopyAll(new DirectoryInfo(context.IPARoot), new DirectoryInfo(context.ProjectRoot), force,
  156. backup,
  157. null, false);
  158. }
  159. else
  160. {
  161. Console.ForegroundColor = ConsoleColor.Yellow;
  162. Console.WriteLine("Not copying files because newer version already installed");
  163. }
  164. #region Create Plugin Folder
  165. if (!Directory.Exists(context.PluginsFolder))
  166. {
  167. Console.ForegroundColor = ConsoleColor.DarkYellow;
  168. Console.WriteLine("Creating plugins folder... ");
  169. Directory.CreateDirectory(context.PluginsFolder);
  170. Console.ResetColor();
  171. }
  172. #endregion
  173. }
  174. catch (Exception e)
  175. {
  176. Console.ForegroundColor = ConsoleColor.Red;
  177. Fail("Oops! This should not have happened.\n\n" + e);
  178. }
  179. Console.ResetColor();
  180. }
  181. private static void Revert(PatchContext context)
  182. {
  183. Console.ForegroundColor = ConsoleColor.Cyan;
  184. Console.Write("Restoring backup... ");
  185. if (BackupManager.Restore(context))
  186. {
  187. Console.WriteLine("Done!");
  188. }
  189. else
  190. {
  191. Console.WriteLine("Already vanilla or you removed your backups!");
  192. }
  193. if (File.Exists(context.ShortcutPath))
  194. {
  195. Console.WriteLine("Deleting shortcut...");
  196. File.Delete(context.ShortcutPath);
  197. }
  198. Console.WriteLine("");
  199. Console.WriteLine("--- Done reverting ---");
  200. Console.ResetColor();
  201. }
  202. private static void StartIfNeedBe(PatchContext context)
  203. {
  204. if (ArgStart.HasValue)
  205. {
  206. Process.Start(context.Executable, ArgStart.Value);
  207. }
  208. else
  209. {
  210. var argList = Arguments.CmdLine.PositionalArgs.ToList();
  211. argList.Remove(context.Executable);
  212. if (ArgLaunch)
  213. {
  214. Process.Start(context.Executable, Args(argList.ToArray()));
  215. }
  216. }
  217. }
  218. public static IEnumerable<FileInfo> NativePluginInterceptor(FileInfo from, FileInfo to,
  219. DirectoryInfo nativePluginFolder, bool isFlat, Architecture preferredArchitecture)
  220. {
  221. if (to.FullName.StartsWith(nativePluginFolder.FullName))
  222. {
  223. var relevantBit = to.FullName.Substring(nativePluginFolder.FullName.Length + 1);
  224. // Goes into the plugin folder!
  225. bool isFileFlat = !relevantBit.StartsWith("x86");
  226. if (isFlat && !isFileFlat)
  227. {
  228. // Flatten structure
  229. bool is64Bit = relevantBit.StartsWith("x86_64");
  230. if (!is64Bit && preferredArchitecture == Architecture.x86)
  231. {
  232. // 32 bit
  233. yield return new FileInfo(Path.Combine(nativePluginFolder.FullName,
  234. relevantBit.Substring("x86".Length + 1)));
  235. }
  236. else if (is64Bit && (preferredArchitecture == Architecture.x64 ||
  237. preferredArchitecture == Architecture.Unknown))
  238. {
  239. // 64 bit
  240. yield return new FileInfo(Path.Combine(nativePluginFolder.FullName,
  241. relevantBit.Substring("x86_64".Length + 1)));
  242. }
  243. }
  244. else if (!isFlat && isFileFlat)
  245. {
  246. // Deepen structure
  247. yield return new FileInfo(Path.Combine(Path.Combine(nativePluginFolder.FullName, "x86"),
  248. relevantBit));
  249. yield return new FileInfo(Path.Combine(Path.Combine(nativePluginFolder.FullName, "x86_64"),
  250. relevantBit));
  251. }
  252. else
  253. {
  254. yield return to;
  255. }
  256. }
  257. else
  258. {
  259. yield return to;
  260. }
  261. }
  262. public static void ClearLine()
  263. {
  264. if (IsConsole)
  265. {
  266. Console.SetCursorPosition(0, Console.CursorTop);
  267. int tpos = Console.CursorTop;
  268. Console.Write(new string(' ', Console.WindowWidth));
  269. Console.SetCursorPosition(0, tpos);
  270. }
  271. }
  272. private static IEnumerable<FileInfo> PassThroughInterceptor(FileInfo from, FileInfo to)
  273. {
  274. yield return to;
  275. }
  276. public static void CopyAll(DirectoryInfo source, DirectoryInfo target, bool aggressive, BackupUnit backup,
  277. Func<FileInfo, FileInfo, IEnumerable<FileInfo>> interceptor = null, bool recurse = true)
  278. {
  279. if (interceptor == null)
  280. {
  281. interceptor = PassThroughInterceptor;
  282. }
  283. // Copy each file into the new directory.
  284. foreach (var fi in source.GetFiles())
  285. {
  286. foreach (var targetFile in interceptor(fi, new FileInfo(Path.Combine(target.FullName, fi.Name))))
  287. {
  288. if (targetFile.Exists && targetFile.LastWriteTimeUtc >= fi.LastWriteTimeUtc && !aggressive)
  289. continue;
  290. Debug.Assert(targetFile.Directory != null, "targetFile.Directory != null");
  291. targetFile.Directory?.Create();
  292. LineBack();
  293. ClearLine();
  294. Console.WriteLine(@"Copying {0}", targetFile.FullName);
  295. backup.Add(targetFile);
  296. fi.CopyTo(targetFile.FullName, true);
  297. }
  298. }
  299. // Copy each subdirectory using recursion.
  300. if (!recurse) return;
  301. foreach (var diSourceSubDir in source.GetDirectories())
  302. {
  303. var nextTargetSubDir = new DirectoryInfo(Path.Combine(target.FullName, diSourceSubDir.Name));
  304. CopyAll(diSourceSubDir, nextTargetSubDir, aggressive, backup, interceptor);
  305. }
  306. }
  307. private static void Fail(string message)
  308. {
  309. Console.Error.WriteLine("ERROR: " + message);
  310. WaitForEnd();
  311. Environment.Exit(1);
  312. }
  313. public static string Args(params string[] args)
  314. {
  315. return string.Join(" ", args.Select(EncodeParameterArgument).ToArray());
  316. }
  317. /// <summary>
  318. /// Encodes an argument for passing into a program
  319. /// </summary>
  320. /// <param name="original">The value_ that should be received by the program</param>
  321. /// <returns>The value_ which needs to be passed to the program for the original value_
  322. /// to come through</returns>
  323. public static string EncodeParameterArgument(string original)
  324. {
  325. if (string.IsNullOrEmpty(original))
  326. return original;
  327. string value = Regex.Replace(original, @"(\\*)" + "\"", @"$1\$0");
  328. value = Regex.Replace(value, @"^(.*\s.*?)(\\*)$", "\"$1$2$2\"");
  329. return value;
  330. }
  331. public static Architecture DetectArchitecture(string assembly)
  332. {
  333. using (var reader = new BinaryReader(File.OpenRead(assembly)))
  334. {
  335. var header = reader.ReadUInt16();
  336. if (header == 0x5a4d)
  337. {
  338. reader.BaseStream.Seek(60, SeekOrigin.Begin); // this location contains the offset for the PE header
  339. var peOffset = reader.ReadUInt32();
  340. reader.BaseStream.Seek(peOffset + 4, SeekOrigin.Begin);
  341. var machine = reader.ReadUInt16();
  342. if (machine == 0x8664) // IMAGE_FILE_MACHINE_AMD64
  343. return Architecture.x64;
  344. if (machine == 0x014c) // IMAGE_FILE_MACHINE_I386
  345. return Architecture.x86;
  346. if (machine == 0x0200) // IMAGE_FILE_MACHINE_IA64
  347. return Architecture.x64;
  348. return Architecture.Unknown;
  349. }
  350. // Not a supported binary
  351. return Architecture.Unknown;
  352. }
  353. }
  354. public static void ResetLine()
  355. {
  356. if (IsConsole)
  357. Console.CursorLeft = 0;
  358. else
  359. Console.Write("\r");
  360. }
  361. public static void LineBack()
  362. {
  363. if (IsConsole)
  364. Console.CursorTop--;
  365. else
  366. Console.Write("\x1b[1A");
  367. }
  368. [DllImport("kernel32.dll")]
  369. private static extern IntPtr GetConsoleWindow();
  370. private static bool? isConsole;
  371. public static bool IsConsole
  372. {
  373. get
  374. {
  375. if (isConsole == null)
  376. isConsole = GetConsoleWindow() != IntPtr.Zero;
  377. return isConsole.Value;
  378. }
  379. }
  380. public abstract class Keyboard
  381. {
  382. [Flags]
  383. private enum KeyStates
  384. {
  385. None = 0,
  386. Down = 1,
  387. Toggled = 2
  388. }
  389. [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
  390. private static extern short GetKeyState(int keyCode);
  391. private static KeyStates KeyState(Keys key)
  392. {
  393. KeyStates state = KeyStates.None;
  394. short retVal = GetKeyState((int)key);
  395. //If the high-order bit is 1, the key is down
  396. //otherwise, it is up.
  397. if ((retVal & 0x8000) == 0x8000)
  398. state |= KeyStates.Down;
  399. //If the low-order bit is 1, the key is toggled.
  400. if ((retVal & 1) == 1)
  401. state |= KeyStates.Toggled;
  402. return state;
  403. }
  404. public static bool IsKeyDown(Keys key)
  405. {
  406. return KeyStates.Down == (KeyState(key) & KeyStates.Down);
  407. }
  408. public static bool IsKeyToggled(Keys key)
  409. {
  410. return KeyStates.Toggled == (KeyState(key) & KeyStates.Toggled);
  411. }
  412. }
  413. }
  414. }