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.

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