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.

433 lines
16 KiB

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