HotPatchManifest.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Security.Cryptography;
  5. using System.Text.RegularExpressions;
  6. using UnityEngine;
  7. namespace HotPatch
  8. {
  9. [Serializable]
  10. public sealed class HotPatchManifest
  11. {
  12. public int schemaVersion = 4;
  13. public string platform;
  14. public string playerBuildId;
  15. public string version;
  16. public string assemblyName;
  17. public string gameSceneName;
  18. public string gameScenePath;
  19. public bool developmentBuild;
  20. public HotPatchResource[] resources = Array.Empty<HotPatchResource>();
  21. public HotPatchResource[] aotBundles = Array.Empty<HotPatchResource>();
  22. public HotPatchResource aotBundle
  23. {
  24. get => (aotBundles ?? Array.Empty<HotPatchResource>()).SingleOrDefault();
  25. set => aotBundles = value == null ? Array.Empty<HotPatchResource>() : new[] { value };
  26. }
  27. public HotPatchResource[] aotMetadata = Array.Empty<HotPatchResource>();
  28. public void Validate(string expectedAssembly, string expectedPlatform, string expectedScene = null)
  29. {
  30. if (schemaVersion != 4 || (aotBundles?.Length ?? 0) > 1 || assemblyName != expectedAssembly || platform != expectedPlatform ||
  31. string.IsNullOrWhiteSpace(gameSceneName) || (expectedScene != null && gameSceneName != expectedScene) ||
  32. !IsScenePath(gameScenePath, gameSceneName) ||
  33. string.IsNullOrWhiteSpace(playerBuildId) || string.IsNullOrWhiteSpace(version) || resources == null || resources.Length == 0)
  34. throw new InvalidDataException("Invalid resource manifest version, platform, assembly, or scene. Use schemaVersion 4 bundle resources.");
  35. var names = new System.Collections.Generic.HashSet<string>(StringComparer.OrdinalIgnoreCase);
  36. int assemblies = 0, scenes = 0;
  37. foreach (var resource in resources)
  38. {
  39. if (resource == null || !HotPatchResource.IsBundleName(resource.name) || !names.Add(resource.name) ||
  40. resource.size <= 0 || !HotPatchHash.IsValid(resource.sha256))
  41. throw new InvalidDataException("Resource names are duplicate or unsafe, or a valid size / SHA-256 is missing.");
  42. if (resource.kind == HotPatchResource.AssemblyKind)
  43. {
  44. if (resource.name != HotPatchResource.AssemblyBundleName(assemblyName)) throw new InvalidDataException("Invalid hot-update bundle name in the manifest.");
  45. assemblies++;
  46. }
  47. else if (resource.kind == HotPatchResource.SceneKind)
  48. {
  49. if (resource.name != HotPatchResource.SceneBundleName(gameSceneName)) throw new InvalidDataException("Invalid scene bundle name in the manifest.");
  50. scenes++;
  51. }
  52. else throw new InvalidDataException("Update resources can contain only hot-update assembly and scene bundles: " + resource.kind);
  53. }
  54. if (assemblies != 1 || scenes != 1) throw new InvalidDataException("The resource manifest must contain one hot-update assembly bundle and one scene bundle.");
  55. if (aotBundle != null && (aotBundle.name != "aot.bundle" || aotBundle.kind != HotPatchResource.AotBundleKind ||
  56. aotBundle.size <= 0 || !HotPatchHash.IsValid(aotBundle.sha256)))
  57. throw new InvalidDataException("Invalid AOT bundle manifest.");
  58. foreach (var resource in aotMetadata ?? Array.Empty<HotPatchResource>())
  59. if (resource == null || resource.kind != HotPatchResource.AotKind || !HotPatchResource.IsValidName(resource.name) ||
  60. !names.Add(resource.name) || resource.size <= 0 || !HotPatchHash.IsValid(resource.sha256))
  61. throw new InvalidDataException("Invalid installed AOT metadata manifest.");
  62. }
  63. public void ValidateAgainst(HotPatchManifest original)
  64. {
  65. if (original == null) throw new ArgumentNullException(nameof(original));
  66. Validate(original.assemblyName, original.platform, original.gameSceneName);
  67. if (playerBuildId != original.playerBuildId || developmentBuild != original.developmentBuild)
  68. throw new InvalidDataException("Update resources are incompatible with the installed AOT baseline. Update the application package.");
  69. if (aotBundle != null && !aotBundle.SameContent(original.aotBundle))
  70. throw new InvalidDataException("The AOT bundle cannot be replaced by a remote update.");
  71. var aot = aotMetadata ?? Array.Empty<HotPatchResource>();
  72. var bundledAot = original.aotMetadata ?? Array.Empty<HotPatchResource>();
  73. if (aot.Length != 0 && (aot.Length != bundledAot.Length || aot.Any(r => !bundledAot.Any(r.SameContent))))
  74. throw new InvalidDataException("AOT metadata must be extracted from the application package and cannot be replaced by a remote update.");
  75. }
  76. public bool SameVersion(HotPatchManifest other) => other != null && schemaVersion == other.schemaVersion &&
  77. assemblyName == other.assemblyName && platform == other.platform && playerBuildId == other.playerBuildId &&
  78. gameSceneName == other.gameSceneName && gameScenePath == other.gameScenePath &&
  79. ((aotBundle == null && other.aotBundle == null) || (aotBundle != null && aotBundle.SameContent(other.aotBundle))) &&
  80. developmentBuild == other.developmentBuild && version == other.version &&
  81. SameResources(resources, other.resources) && SameResources(aotMetadata, other.aotMetadata);
  82. static bool SameResources(HotPatchResource[] first, HotPatchResource[] second)
  83. {
  84. first = first ?? Array.Empty<HotPatchResource>(); second = second ?? Array.Empty<HotPatchResource>();
  85. return first.Length == second.Length && first.All(r => second.Any(r.SameContent));
  86. }
  87. public HotPatchResource AssemblyResource => resources.Single(r => r.kind == HotPatchResource.AssemblyKind);
  88. public HotPatchResource SceneResource => resources.Single(r => r.kind == HotPatchResource.SceneKind);
  89. public static bool IsScenePath(string path, string scene) => !string.IsNullOrEmpty(path) &&
  90. path.StartsWith("Assets/", StringComparison.Ordinal) && !path.Contains("..") && !path.Contains('\\') &&
  91. path.EndsWith(".unity", StringComparison.OrdinalIgnoreCase) && Path.GetFileNameWithoutExtension(path) == scene;
  92. }
  93. [Serializable]
  94. public sealed class HotPatchResource
  95. {
  96. public const string AssemblyKind = "assembly-bundle";
  97. public const string SceneKind = "scene-bundle";
  98. public const string AotBundleKind = "aot-bundle";
  99. public const string AotKind = "aot";
  100. public string name;
  101. public string kind;
  102. public long size;
  103. public string sha256;
  104. public string RelativePath
  105. {
  106. get
  107. {
  108. if (!HotPatchHash.IsValid(sha256)) throw new InvalidDataException("Invalid resource SHA-256.");
  109. if (kind == AotBundleKind) return "aot.bundle";
  110. if (kind == AotKind)
  111. {
  112. if (!IsValidName(name)) throw new InvalidDataException("Invalid AOT file name.");
  113. return name + ".bytes";
  114. }
  115. return "files/" + sha256.ToLowerInvariant() + ".bundle";
  116. }
  117. }
  118. public bool SameContent(HotPatchResource other) => other != null && name == other.name && kind == other.kind &&
  119. size == other.size && string.Equals(sha256, other.sha256, StringComparison.OrdinalIgnoreCase);
  120. public static bool IsValidName(string value) => value != null &&
  121. Regex.IsMatch(value, @"\A[\p{L}\p{N}_.-]+\.dll\z") && !value.Contains("..");
  122. public static bool IsBundleName(string value) => value != null &&
  123. Regex.IsMatch(value, @"\A[\p{L}\p{N}_. -]+\.bundle\z") && !value.Contains("..");
  124. public static string AssemblyBundleName(string name) => "hotupdate." + name.ToLowerInvariant() + ".bundle";
  125. public static string SceneBundleName(string name) => "scene." + name.ToLowerInvariant() + ".bundle";
  126. }
  127. public readonly struct HotPatchProgress
  128. {
  129. public readonly string Stage;
  130. public readonly float Value;
  131. public readonly ulong DownloadedBytes;
  132. public readonly long TotalBytes;
  133. public HotPatchProgress(string stage, float value, ulong downloaded = 0, long total = 0)
  134. { Stage = stage; Value = Mathf.Clamp01(value); DownloadedBytes = downloaded; TotalBytes = total; }
  135. }
  136. public static class HotPatchHash
  137. {
  138. public static bool IsValid(string value) => value != null && Regex.IsMatch(value, "\\A[0-9a-fA-F]{64}\\z");
  139. public static string Of(byte[] bytes)
  140. {
  141. using var sha = SHA256.Create();
  142. return BitConverter.ToString(sha.ComputeHash(bytes)).Replace("-", "").ToLowerInvariant();
  143. }
  144. public static string OfFile(string path)
  145. {
  146. using var stream = File.OpenRead(path);
  147. using var sha = SHA256.Create();
  148. return BitConverter.ToString(sha.ComputeHash(stream)).Replace("-", "").ToLowerInvariant();
  149. }
  150. public static void RequireHttp(Uri uri)
  151. {
  152. if (uri == null || !uri.IsAbsoluteUri || (uri.Scheme != "https" && uri.Scheme != "http"))
  153. throw new InvalidDataException("The hot patch URL must be an absolute HTTP(S) URL.");
  154. }
  155. }
  156. }