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.

599 lines
22 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. using IPA.Utilities;
  2. using IPA.Loader;
  3. using Ionic.Zip;
  4. using Newtonsoft.Json;
  5. using System;
  6. using System.Collections;
  7. using System.Collections.Generic;
  8. using System.Diagnostics;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Security.Cryptography;
  12. using System.Text;
  13. using System.Text.RegularExpressions;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. using UnityEngine;
  17. using UnityEngine.Networking;
  18. using SemVer;
  19. using Logger = IPA.Logging.Logger;
  20. using Version = SemVer.Version;
  21. using IPA.Updating.Backup;
  22. using System.Runtime.Serialization;
  23. using System.Reflection;
  24. using static IPA.Loader.PluginManager;
  25. namespace IPA.Updating.ModsaberML
  26. {
  27. class Updater : MonoBehaviour
  28. {
  29. public static Updater instance;
  30. public void Awake()
  31. {
  32. try
  33. {
  34. if (instance != null)
  35. Destroy(this);
  36. else
  37. {
  38. instance = this;
  39. CheckForUpdates();
  40. }
  41. }
  42. catch (Exception e)
  43. {
  44. Logger.updater.Error(e);
  45. }
  46. }
  47. private void CheckForUpdates()
  48. {
  49. StartCoroutine(CheckForUpdatesCoroutine());
  50. }
  51. private class DependencyObject
  52. {
  53. public string Name { get; set; }
  54. public Version Version { get; set; } = null;
  55. public Version ResolvedVersion { get; set; } = null;
  56. public Range Requirement { get; set; } = null;
  57. public Range Conflicts { get; set; } = null;
  58. public bool Resolved { get; set; } = false;
  59. public bool Has { get; set; } = false;
  60. public HashSet<string> Consumers { get; set; } = new HashSet<string>();
  61. public bool MetaRequestFailed { get; set; } = false;
  62. public BSPluginMeta LocalPluginMeta { get; set; } = null;
  63. public override string ToString()
  64. {
  65. return $"{Name}@{Version}{(Resolved ? $" -> {ResolvedVersion}" : "")} - ({Requirement} ! {Conflicts}) {(Has ? $" Already have" : "")}";
  66. }
  67. }
  68. private Dictionary<string, string> requestCache = new Dictionary<string, string>();
  69. private IEnumerator GetModsaberEndpoint(string url, Ref<string> result)
  70. {
  71. if (requestCache.TryGetValue(url, out string value))
  72. {
  73. result.Value = value;
  74. yield break;
  75. }
  76. else
  77. {
  78. using (var request = UnityWebRequest.Get(ApiEndpoint.ApiBase + url))
  79. {
  80. yield return request.SendWebRequest();
  81. if (request.isNetworkError)
  82. {
  83. result.Error = new NetworkException($"Network error while trying to download: {request.error}");
  84. yield break;
  85. }
  86. if (request.isHttpError)
  87. {
  88. if (request.responseCode == 404)
  89. {
  90. result.Error = new NetworkException("Not found");
  91. yield break;
  92. }
  93. result.Error = new NetworkException($"Server returned error {request.error} while getting data");
  94. yield break;
  95. }
  96. result.Value = request.downloadHandler.text;
  97. requestCache[url] = result.Value;
  98. }
  99. }
  100. }
  101. private Dictionary<string, ApiEndpoint.Mod> modCache = new Dictionary<string, ApiEndpoint.Mod>();
  102. private IEnumerator GetModInfo(string name, string ver, Ref<ApiEndpoint.Mod> result)
  103. {
  104. var uri = string.Format(ApiEndpoint.GetModInfoEndpoint, Uri.EscapeUriString(name), Uri.EscapeUriString(ver));
  105. if (modCache.TryGetValue(uri, out ApiEndpoint.Mod value))
  106. {
  107. result.Value = value;
  108. yield break;
  109. }
  110. else
  111. {
  112. Ref<string> reqResult = new Ref<string>("");
  113. yield return GetModsaberEndpoint(uri, reqResult);
  114. try
  115. {
  116. result.Value = JsonConvert.DeserializeObject<ApiEndpoint.Mod>(reqResult.Value);
  117. modCache[uri] = result.Value;
  118. }
  119. catch (Exception e)
  120. {
  121. result.Error = new Exception("Error decoding response", e);
  122. yield break;
  123. }
  124. }
  125. }
  126. private Dictionary<string, List<ApiEndpoint.Mod>> modVersionsCache = new Dictionary<string, List<ApiEndpoint.Mod>>();
  127. private IEnumerator GetModVersionsMatching(string name, string range, Ref<List<ApiEndpoint.Mod>> result)
  128. {
  129. var uri = string.Format(ApiEndpoint.GetModsWithSemver, Uri.EscapeUriString(name), Uri.EscapeUriString(range));
  130. if (modVersionsCache.TryGetValue(uri, out List<ApiEndpoint.Mod> value))
  131. {
  132. result.Value = value;
  133. yield break;
  134. }
  135. else
  136. {
  137. Ref<string> reqResult = new Ref<string>("");
  138. yield return GetModsaberEndpoint(uri, reqResult);
  139. try
  140. {
  141. result.Value = JsonConvert.DeserializeObject<List<ApiEndpoint.Mod>>(reqResult.Value);
  142. modVersionsCache[uri] = result.Value;
  143. }
  144. catch (Exception e)
  145. {
  146. result.Error = new Exception("Error decoding response", e);
  147. yield break;
  148. }
  149. }
  150. }
  151. private IEnumerator CheckForUpdatesCoroutine()
  152. {
  153. var depList = new Ref<List<DependencyObject>>(new List<DependencyObject>());
  154. foreach (var plugin in BSMetas)
  155. { // initialize with data to resolve (1.1)
  156. if (plugin.ModsaberInfo != null)
  157. { // updatable
  158. var msinfo = plugin.ModsaberInfo;
  159. depList.Value.Add(new DependencyObject {
  160. Name = msinfo.InternalName,
  161. Version = new Version(msinfo.CurrentVersion),
  162. Requirement = new Range($">={msinfo.CurrentVersion}"),
  163. LocalPluginMeta = plugin
  164. });
  165. }
  166. }
  167. foreach (var dep in depList.Value)
  168. Logger.updater.Debug($"Phantom Dependency: {dep.ToString()}");
  169. yield return DependencyResolveFirstPass(depList);
  170. foreach (var dep in depList.Value)
  171. Logger.updater.Debug($"Dependency: {dep.ToString()}");
  172. yield return DependencyResolveSecondPass(depList);
  173. foreach (var dep in depList.Value)
  174. Logger.updater.Debug($"Dependency: {dep.ToString()}");
  175. DependendyResolveFinalPass(depList);
  176. }
  177. private IEnumerator DependencyResolveFirstPass(Ref<List<DependencyObject>> list)
  178. {
  179. for (int i = 0; i < list.Value.Count; i++)
  180. { // Grab dependencies (1.2)
  181. var dep = list.Value[i];
  182. var mod = new Ref<ApiEndpoint.Mod>(null);
  183. #region TEMPORARY get latest // SHOULD BE GREATEST OF VERSION // not going to happen because of disagreements with ModSaber
  184. yield return GetModInfo(dep.Name, "", mod);
  185. #endregion
  186. try { mod.Verify(); }
  187. catch (Exception e)
  188. {
  189. Logger.updater.Error($"Error getting info for {dep.Name}");
  190. Logger.updater.Error(e);
  191. dep.MetaRequestFailed = true;
  192. continue;
  193. }
  194. list.Value.AddRange(mod.Value.Dependencies.Select(d => new DependencyObject { Name = d.Name, Requirement = d.VersionRange, Consumers = new HashSet<string>() { dep.Name } }));
  195. list.Value.AddRange(mod.Value.Conflicts.Select(d => new DependencyObject { Name = d.Name, Conflicts = d.VersionRange, Consumers = new HashSet<string>() { dep.Name } }));
  196. }
  197. var depNames = new HashSet<string>();
  198. var final = new List<DependencyObject>();
  199. foreach (var dep in list.Value)
  200. { // agregate ranges and the like (1.3)
  201. if (!depNames.Contains(dep.Name))
  202. { // should add it
  203. depNames.Add(dep.Name);
  204. final.Add(dep);
  205. }
  206. else
  207. {
  208. var toMod = final.Where(d => d.Name == dep.Name).First();
  209. if (dep.Requirement != null)
  210. {
  211. toMod.Requirement = toMod.Requirement.Intersect(dep.Requirement);
  212. foreach (var consume in dep.Consumers)
  213. toMod.Consumers.Add(consume);
  214. }
  215. else if (dep.Conflicts != null)
  216. {
  217. if (toMod.Conflicts == null)
  218. toMod.Conflicts = dep.Conflicts;
  219. else
  220. toMod.Conflicts = new Range($"{toMod.Conflicts} || {dep.Conflicts}"); // there should be a better way to do this
  221. }
  222. }
  223. }
  224. list.Value = final;
  225. }
  226. private IEnumerator DependencyResolveSecondPass(Ref<List<DependencyObject>> list)
  227. {
  228. foreach(var dep in list.Value)
  229. {
  230. dep.Has = dep.Version != null;// dep.Version is only not null if its already installed
  231. if (dep.MetaRequestFailed)
  232. {
  233. Logger.updater.Warn($"{dep.Name} info request failed, not trying again");
  234. continue;
  235. }
  236. var modsMatching = new Ref<List<ApiEndpoint.Mod>>(null);
  237. yield return GetModVersionsMatching(dep.Name, dep.Requirement.ToString(), modsMatching);
  238. try { modsMatching.Verify(); }
  239. catch (Exception e)
  240. {
  241. Logger.updater.Error($"Error getting mod list for {dep.Name}");
  242. Logger.updater.Error(e);
  243. dep.MetaRequestFailed = true;
  244. continue;
  245. }
  246. var ver = modsMatching.Value.Where(val => val.GameVersion == BeatSaber.GameVersion && val.Approved && !dep.Conflicts.IsSatisfied(val.Version)).Select(mod => mod.Version).Max(); // (2.1)
  247. if (dep.Resolved = ver != null) dep.ResolvedVersion = ver; // (2.2)
  248. dep.Has = dep.Version == dep.ResolvedVersion && dep.Resolved; // dep.Version is only not null if its already installed
  249. }
  250. }
  251. private void DependendyResolveFinalPass(Ref<List<DependencyObject>> list)
  252. { // also starts download of mods
  253. var toDl = new List<DependencyObject>();
  254. foreach (var dep in list.Value)
  255. { // figure out which ones need to be downloaded (3.1)
  256. if (dep.Resolved)
  257. {
  258. Logger.updater.Debug($"Resolved: {dep.ToString()}");
  259. if (!dep.Has)
  260. {
  261. Logger.updater.Debug($"To Download: {dep.ToString()}");
  262. toDl.Add(dep);
  263. }
  264. }
  265. else if (!dep.Has)
  266. {
  267. Logger.updater.Warn($"Could not resolve dependency {dep}");
  268. }
  269. }
  270. Logger.updater.Debug($"To Download {string.Join(", ", toDl.Select(d => $"{d.Name}@{d.ResolvedVersion}"))}");
  271. string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + Path.GetRandomFileName());
  272. Directory.CreateDirectory(tempDirectory);
  273. Logger.updater.Debug($"Temp directory: {tempDirectory}");
  274. foreach (var item in toDl)
  275. StartCoroutine(UpdateModCoroutine(item, tempDirectory));
  276. }
  277. private IEnumerator UpdateModCoroutine(DependencyObject item, string tempDirectory)
  278. { // (3.2)
  279. Logger.updater.Debug($"Release: {BeatSaber.ReleaseType}");
  280. var mod = new Ref<ApiEndpoint.Mod>(null);
  281. yield return GetModInfo(item.Name, item.ResolvedVersion.ToString(), mod);
  282. try { mod.Verify(); }
  283. catch (Exception e)
  284. {
  285. Logger.updater.Error($"Error occurred while trying to get information for {item}");
  286. Logger.updater.Error(e);
  287. yield break;
  288. }
  289. ApiEndpoint.Mod.PlatformFile platformFile;
  290. if (BeatSaber.ReleaseType == BeatSaber.Release.Steam || mod.Value.Files.Oculus == null)
  291. platformFile = mod.Value.Files.Steam;
  292. else
  293. platformFile = mod.Value.Files.Oculus;
  294. string url = platformFile.DownloadPath;
  295. Logger.updater.Debug($"URL = {url}");
  296. const int MaxTries = 3;
  297. int maxTries = MaxTries;
  298. while (maxTries > 0)
  299. {
  300. if (maxTries-- != MaxTries)
  301. Logger.updater.Debug($"Re-trying download...");
  302. using (var stream = new MemoryStream())
  303. using (var request = UnityWebRequest.Get(url))
  304. using (var taskTokenSource = new CancellationTokenSource())
  305. {
  306. var dlh = new StreamDownloadHandler(stream);
  307. request.downloadHandler = dlh;
  308. Logger.updater.Debug("Sending request");
  309. //Logger.updater.Debug(request?.downloadHandler?.ToString() ?? "DLH==NULL");
  310. yield return request.SendWebRequest();
  311. Logger.updater.Debug("Download finished");
  312. if (request.isNetworkError)
  313. {
  314. Logger.updater.Error("Network error while trying to update mod");
  315. Logger.updater.Error(request.error);
  316. taskTokenSource.Cancel();
  317. continue;
  318. }
  319. if (request.isHttpError)
  320. {
  321. Logger.updater.Error($"Server returned an error code while trying to update mod");
  322. Logger.updater.Error(request.error);
  323. taskTokenSource.Cancel();
  324. continue;
  325. }
  326. stream.Seek(0, SeekOrigin.Begin); // reset to beginning
  327. var downloadTask = Task.Run(() =>
  328. { // use slightly more multithreaded approach than coroutines
  329. ExtractPluginAsync(stream, item, platformFile, tempDirectory);
  330. }, taskTokenSource.Token);
  331. while (!(downloadTask.IsCompleted || downloadTask.IsCanceled || downloadTask.IsFaulted))
  332. yield return null; // pause coroutine until task is done
  333. if (downloadTask.IsFaulted)
  334. {
  335. if (downloadTask.Exception.InnerExceptions.Where(e => e is ModsaberInterceptException).Any())
  336. { // any exception is an intercept exception
  337. Logger.updater.Error($"Modsaber did not return expected data for {item.Name}");
  338. }
  339. Logger.updater.Error($"Error downloading mod {item.Name}");
  340. Logger.updater.Error(downloadTask.Exception);
  341. continue;
  342. }
  343. break;
  344. }
  345. }
  346. if (maxTries == 0)
  347. Logger.updater.Warn($"Plugin download failed {MaxTries} times, not re-trying");
  348. else
  349. Logger.updater.Debug("Download complete");
  350. }
  351. internal class StreamDownloadHandler : DownloadHandlerScript
  352. {
  353. public MemoryStream Stream { get; set; }
  354. public StreamDownloadHandler(MemoryStream stream) : base()
  355. {
  356. Stream = stream;
  357. }
  358. protected override void ReceiveContentLength(int contentLength)
  359. {
  360. Stream.Capacity = contentLength;
  361. Logger.updater.Debug($"Got content length: {contentLength}");
  362. }
  363. protected override void CompleteContent()
  364. {
  365. Logger.updater.Debug("Download complete");
  366. }
  367. protected override bool ReceiveData(byte[] data, int dataLength)
  368. {
  369. if (data == null || data.Length < 1)
  370. {
  371. Logger.updater.Debug("CustomWebRequest :: ReceiveData - received a null/empty buffer");
  372. return false;
  373. }
  374. Stream.Write(data, 0, dataLength);
  375. return true;
  376. }
  377. protected override byte[] GetData() { return null; }
  378. protected override float GetProgress()
  379. {
  380. return 0f;
  381. }
  382. public override string ToString()
  383. {
  384. return $"{base.ToString()} ({Stream?.ToString()})";
  385. }
  386. }
  387. private void ExtractPluginAsync(MemoryStream stream, DependencyObject item, ApiEndpoint.Mod.PlatformFile fileInfo, string tempDirectory)
  388. { // (3.3)
  389. Logger.updater.Debug($"Extracting ZIP file for {item.Name}");
  390. var data = stream.GetBuffer();
  391. SHA1 sha = new SHA1CryptoServiceProvider();
  392. var hash = sha.ComputeHash(data);
  393. if (!LoneFunctions.UnsafeCompare(hash, fileInfo.Hash))
  394. throw new Exception("The hash for the file doesn't match what is defined");
  395. var newFiles = new List<FileInfo>();
  396. var backup = new BackupUnit(tempDirectory, $"backup-{item.Name}");
  397. try
  398. {
  399. bool shouldDeleteOldFile = true;
  400. using (var zipFile = ZipFile.Read(stream))
  401. {
  402. Logger.updater.Debug("Streams opened");
  403. foreach (var entry in zipFile)
  404. {
  405. if (entry.IsDirectory)
  406. {
  407. Logger.updater.Debug($"Creating directory {entry.FileName}");
  408. Directory.CreateDirectory(Path.Combine(Environment.CurrentDirectory, entry.FileName));
  409. }
  410. else
  411. {
  412. using (var ostream = new MemoryStream((int)entry.UncompressedSize))
  413. {
  414. entry.Extract(ostream);
  415. ostream.Seek(0, SeekOrigin.Begin);
  416. sha = new SHA1CryptoServiceProvider();
  417. var fileHash = sha.ComputeHash(ostream);
  418. try
  419. {
  420. if (!LoneFunctions.UnsafeCompare(fileHash, fileInfo.FileHashes[entry.FileName]))
  421. throw new Exception("The hash for the file doesn't match what is defined");
  422. }
  423. catch (KeyNotFoundException)
  424. {
  425. throw new ModsaberInterceptException("ModSaber did not send the hashes for the zip's content!");
  426. }
  427. ostream.Seek(0, SeekOrigin.Begin);
  428. FileInfo targetFile = new FileInfo(Path.Combine(Environment.CurrentDirectory, entry.FileName));
  429. Directory.CreateDirectory(targetFile.DirectoryName);
  430. if (targetFile.FullName == item.LocalPluginMeta?.Filename)
  431. shouldDeleteOldFile = false; // overwriting old file, no need to delete
  432. if (targetFile.Exists)
  433. backup.Add(targetFile);
  434. else
  435. newFiles.Add(targetFile);
  436. Logger.updater.Debug($"Extracting file {targetFile.FullName}");
  437. targetFile.Delete();
  438. var fstream = targetFile.Create();
  439. ostream.CopyTo(fstream);
  440. }
  441. }
  442. }
  443. }
  444. if (item.LocalPluginMeta?.Plugin is SelfPlugin)
  445. { // currently updating self
  446. Process.Start(new ProcessStartInfo
  447. {
  448. FileName = item.LocalPluginMeta.Filename,
  449. Arguments = $"-nw={Process.GetCurrentProcess().Id}",
  450. UseShellExecute = false
  451. });
  452. }
  453. else if (shouldDeleteOldFile && item.LocalPluginMeta != null)
  454. File.Delete(item.LocalPluginMeta.Filename);
  455. }
  456. catch (Exception)
  457. { // something failed; restore
  458. foreach (var file in newFiles)
  459. file.Delete();
  460. backup.Restore();
  461. backup.Delete();
  462. throw;
  463. }
  464. backup.Delete();
  465. Logger.updater.Debug("Extractor exited");
  466. }
  467. }
  468. [Serializable]
  469. internal class NetworkException : Exception
  470. {
  471. public NetworkException()
  472. {
  473. }
  474. public NetworkException(string message) : base(message)
  475. {
  476. }
  477. public NetworkException(string message, Exception innerException) : base(message, innerException)
  478. {
  479. }
  480. protected NetworkException(SerializationInfo info, StreamingContext context) : base(info, context)
  481. {
  482. }
  483. }
  484. [Serializable]
  485. internal class ModsaberInterceptException : Exception
  486. {
  487. public ModsaberInterceptException()
  488. {
  489. }
  490. public ModsaberInterceptException(string message) : base(message)
  491. {
  492. }
  493. public ModsaberInterceptException(string message, Exception innerException) : base(message, innerException)
  494. {
  495. }
  496. protected ModsaberInterceptException(SerializationInfo info, StreamingContext context) : base(info, context)
  497. {
  498. }
  499. }
  500. }