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.

421 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
  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.6.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. argExeName ??= new DirectoryInfo(Directory.GetCurrentDirectory()).GetFiles()
  81. .FirstOrDefault(o => o.Extension == ".exe" && o.FullName != Assembly.GetEntryAssembly().Location)
  82. ?.FullName;
  83. if (argExeName == null)
  84. {
  85. Fail("Could not locate game executable");
  86. }
  87. else
  88. context = PatchContext.Create(argExeName);
  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. Revert(context);
  102. else
  103. {
  104. Install(context);
  105. StartIfNeedBe(context);
  106. }
  107. }
  108. catch (Exception e)
  109. {
  110. if (ArgVersion)
  111. {
  112. Console.WriteLine("No currently installed version");
  113. return;
  114. }
  115. Fail(e.Message);
  116. }
  117. WaitForEnd();
  118. }
  119. private static void WaitForEnd()
  120. {
  121. if (!ArgNoWait)
  122. {
  123. Console.ForegroundColor = ConsoleColor.DarkYellow;
  124. Console.WriteLine("[Press any key to continue]");
  125. Console.ResetColor();
  126. Console.ReadKey();
  127. }
  128. }
  129. private static void Validate(PatchContext c)
  130. {
  131. if (!Directory.Exists(c.DataPathDst) || !File.Exists(c.EngineFile))
  132. {
  133. Fail("Game does not seem to be a Unity project. Could not find the libraries to patch.");
  134. Console.WriteLine($"DataPath: {c.DataPathDst}");
  135. Console.WriteLine($"EngineFile: {c.EngineFile}");
  136. }
  137. }
  138. private static Version GetInstalledVersion(PatchContext context)
  139. {
  140. // first, check currently installed version, if any
  141. if (File.Exists(Path.Combine(context.ProjectRoot, "winhttp.dll")))
  142. { // installed, so check version of installed assembly
  143. string injectorPath = Path.Combine(context.ManagedPath, "IPA.Injector.dll");
  144. if (File.Exists(injectorPath))
  145. {
  146. var verInfo = FileVersionInfo.GetVersionInfo(injectorPath);
  147. var fileVersion = new Version(verInfo.FileVersion);
  148. return fileVersion;
  149. }
  150. }
  151. return null;
  152. }
  153. private static void Install(PatchContext context)
  154. {
  155. try
  156. {
  157. bool installFiles = true;
  158. var fileVersion = GetInstalledVersion(context);
  159. if (fileVersion != null && fileVersion > Version)
  160. installFiles = false;
  161. if (installFiles || ArgForce)
  162. {
  163. var backup = new BackupUnit(context);
  164. if (!ArgNoRevert)
  165. {
  166. Console.ForegroundColor = ConsoleColor.Cyan;
  167. Console.WriteLine("Restoring old version... ");
  168. if (BackupManager.HasBackup(context))
  169. BackupManager.Restore(context);
  170. }
  171. var nativePluginFolder = Path.Combine(context.DataPathDst, "Plugins");
  172. bool isFlat = Directory.Exists(nativePluginFolder) &&
  173. Directory.GetFiles(nativePluginFolder).Any(f => f.EndsWith(".dll"));
  174. bool force = !BackupManager.HasBackup(context) || ArgForce;
  175. var architecture = DetectArchitecture(context.Executable);
  176. Console.ForegroundColor = ConsoleColor.DarkCyan;
  177. Console.WriteLine("Installing files... ");
  178. CopyAll(new DirectoryInfo(context.DataPathSrc), new DirectoryInfo(context.DataPathDst), force,
  179. backup);
  180. CopyAll(new DirectoryInfo(context.LibsPathSrc), new DirectoryInfo(context.LibsPathDst), force,
  181. backup);
  182. CopyAll(new DirectoryInfo(context.IPARoot), new DirectoryInfo(context.ProjectRoot), force,
  183. backup,
  184. null, false);
  185. }
  186. else
  187. {
  188. Console.ForegroundColor = ConsoleColor.Yellow;
  189. Console.WriteLine("Not copying files because newer version already installed");
  190. }
  191. #region Create Plugin Folder
  192. if (!Directory.Exists(context.PluginsFolder))
  193. {
  194. Console.ForegroundColor = ConsoleColor.DarkYellow;
  195. Console.WriteLine("Creating plugins folder... ");
  196. Directory.CreateDirectory(context.PluginsFolder);
  197. Console.ResetColor();
  198. }
  199. #endregion
  200. }
  201. catch (Exception e)
  202. {
  203. Console.ForegroundColor = ConsoleColor.Red;
  204. Fail("Oops! This should not have happened.\n\n" + e);
  205. }
  206. Console.ResetColor();
  207. }
  208. private static void Revert(PatchContext context)
  209. {
  210. Console.ForegroundColor = ConsoleColor.Cyan;
  211. Console.Write("Restoring backup... ");
  212. if (BackupManager.Restore(context))
  213. {
  214. Console.WriteLine("Done!");
  215. }
  216. else
  217. {
  218. Console.WriteLine("Already vanilla or you removed your backups!");
  219. }
  220. if (File.Exists(context.ShortcutPath))
  221. {
  222. Console.WriteLine("Deleting shortcut...");
  223. File.Delete(context.ShortcutPath);
  224. }
  225. Console.WriteLine("");
  226. Console.WriteLine("--- Done reverting ---");
  227. Console.ResetColor();
  228. }
  229. private static void StartIfNeedBe(PatchContext context)
  230. {
  231. if (ArgStart.HasValue)
  232. {
  233. Process.Start(context.Executable, ArgStart.Value);
  234. }
  235. else
  236. {
  237. var argList = Arguments.CmdLine.PositionalArgs.ToList();
  238. argList.Remove(context.Executable);
  239. if (ArgLaunch)
  240. {
  241. Process.Start(context.Executable, Args(argList.ToArray()));
  242. }
  243. }
  244. }
  245. public static void ClearLine()
  246. {
  247. if (IsConsole)
  248. {
  249. Console.SetCursorPosition(0, Console.CursorTop);
  250. int tpos = Console.CursorTop;
  251. Console.Write(new string(' ', Console.WindowWidth));
  252. Console.SetCursorPosition(0, tpos);
  253. }
  254. }
  255. private static IEnumerable<FileInfo> PassThroughInterceptor(FileInfo from, FileInfo to)
  256. {
  257. yield return to;
  258. }
  259. public static void CopyAll(DirectoryInfo source, DirectoryInfo target, bool aggressive, BackupUnit backup,
  260. Func<FileInfo, FileInfo, IEnumerable<FileInfo>> interceptor = null, bool recurse = true)
  261. {
  262. if (interceptor == null)
  263. {
  264. interceptor = PassThroughInterceptor;
  265. }
  266. // Copy each file into the new directory.
  267. foreach (var fi in source.GetFiles())
  268. {
  269. foreach (var targetFile in interceptor(fi, new FileInfo(Path.Combine(target.FullName, fi.Name))))
  270. {
  271. if (targetFile.Exists && targetFile.LastWriteTimeUtc >= fi.LastWriteTimeUtc && !aggressive)
  272. continue;
  273. Debug.Assert(targetFile.Directory != null, "targetFile.Directory != null");
  274. targetFile.Directory?.Create();
  275. LineBack();
  276. ClearLine();
  277. Console.WriteLine(@"Copying {0}", targetFile.FullName);
  278. backup.Add(targetFile);
  279. fi.CopyTo(targetFile.FullName, true);
  280. }
  281. }
  282. // Copy each subdirectory using recursion.
  283. if (!recurse) return;
  284. foreach (var diSourceSubDir in source.GetDirectories())
  285. {
  286. var nextTargetSubDir = new DirectoryInfo(Path.Combine(target.FullName, diSourceSubDir.Name));
  287. CopyAll(diSourceSubDir, nextTargetSubDir, aggressive, backup, interceptor);
  288. }
  289. }
  290. [DoesNotReturn]
  291. private static void Fail(string message)
  292. {
  293. Console.Error.WriteLine("ERROR: " + message);
  294. WaitForEnd();
  295. Environment.Exit(1);
  296. }
  297. public static string Args(params string[] args)
  298. {
  299. return string.Join(" ", args.Select(EncodeParameterArgument).ToArray());
  300. }
  301. /// <summary>
  302. /// Encodes an argument for passing into a program
  303. /// </summary>
  304. /// <param name="original">The value_ that should be received by the program</param>
  305. /// <returns>The value_ which needs to be passed to the program for the original value_
  306. /// to come through</returns>
  307. public static string EncodeParameterArgument(string original)
  308. {
  309. if (string.IsNullOrEmpty(original))
  310. return original;
  311. string value = Regex.Replace(original, @"(\\*)" + "\"", @"$1\$0");
  312. value = Regex.Replace(value, @"^(.*\s.*?)(\\*)$", "\"$1$2$2\"");
  313. return value;
  314. }
  315. public static Architecture DetectArchitecture(string assembly)
  316. {
  317. using (var reader = new BinaryReader(File.OpenRead(assembly)))
  318. {
  319. var header = reader.ReadUInt16();
  320. if (header == 0x5a4d)
  321. {
  322. reader.BaseStream.Seek(60, SeekOrigin.Begin); // this location contains the offset for the PE header
  323. var peOffset = reader.ReadUInt32();
  324. reader.BaseStream.Seek(peOffset + 4, SeekOrigin.Begin);
  325. var machine = reader.ReadUInt16();
  326. if (machine == 0x8664) // IMAGE_FILE_MACHINE_AMD64
  327. return Architecture.x64;
  328. if (machine == 0x014c) // IMAGE_FILE_MACHINE_I386
  329. return Architecture.x86;
  330. if (machine == 0x0200) // IMAGE_FILE_MACHINE_IA64
  331. return Architecture.x64;
  332. return Architecture.Unknown;
  333. }
  334. // Not a supported binary
  335. return Architecture.Unknown;
  336. }
  337. }
  338. public static void ResetLine()
  339. {
  340. if (IsConsole)
  341. Console.CursorLeft = 0;
  342. else
  343. Console.Write("\r");
  344. }
  345. public static void LineBack()
  346. {
  347. if (IsConsole)
  348. Console.CursorTop--;
  349. else
  350. Console.Write("\x1b[1A");
  351. }
  352. public static bool IsConsole => Environment.UserInteractive;
  353. }
  354. }