S3ResourceUploader.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Http;
  8. using System.Security.Cryptography;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using System.Xml.Linq;
  13. public sealed class S3UploadFile
  14. {
  15. public string LocalPath;
  16. public string Key;
  17. public long Size;
  18. public bool IsManifest => Path.GetFileName(Key).Equals("manifest.json", StringComparison.OrdinalIgnoreCase)
  19. || Path.GetFileName(Key).Equals("manifest_hot.json", StringComparison.OrdinalIgnoreCase);
  20. }
  21. public static class S3ResourceUploader
  22. {
  23. public static string TargetPrefix(string downloadUrl)
  24. {
  25. if (string.IsNullOrWhiteSpace(downloadUrl))
  26. throw new ArgumentException("请先填写 DownloadUrl,再上传资源。");
  27. if (!Uri.TryCreate(downloadUrl, UriKind.Absolute, out var uri) || (uri.Scheme != "https" && uri.Scheme != "http"))
  28. throw new ArgumentException("DownloadUrl 必须是 HTTP(S) 地址。");
  29. var segments = uri.AbsolutePath.Trim('/').Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).ToList();
  30. if (segments.Count > 0 && segments.Last().EndsWith(".json", StringComparison.OrdinalIgnoreCase)) segments.RemoveAt(segments.Count - 1);
  31. if (segments.Count == 0) throw new ArgumentException("DownloadUrl 必须包含上传目标目录,不能是域名根路径。");
  32. var prefix = Uri.UnescapeDataString(segments.Last());
  33. if (prefix == "." || prefix == ".." || prefix.Any(c => c == '/' || c == '\\' || char.IsControl(c)))
  34. throw new ArgumentException("DownloadUrl 最后一级目录不合法。");
  35. return prefix;
  36. }
  37. public static List<S3UploadFile> CreatePlan(string directory, string prefix)
  38. {
  39. var root = Path.GetFullPath(directory).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
  40. if (root.Length == 0 || root.EndsWith(":")) root += Path.DirectorySeparatorChar;
  41. var rootPrefix = root.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
  42. if (!Directory.Exists(root)) throw new DirectoryNotFoundException("上传目录不存在。");
  43. var files = new List<S3UploadFile>();
  44. Visit(root);
  45. foreach (var file in files)
  46. if (Encoding.UTF8.GetByteCount(file.Key) > 1024 || file.Key.Contains("\\") || file.Key.Any(char.IsControl) || file.Key.Split('/').Any(p => p == "." || p == ".."))
  47. throw new IOException("S3 对象路径不合法或超过 1024 字节: " + file.Key);
  48. return files.OrderBy(f => f.IsManifest ? 1 : 0).ThenBy(f => f.Key, StringComparer.Ordinal).ToList();
  49. void Visit(string current)
  50. {
  51. if ((File.GetAttributes(current) & FileAttributes.ReparsePoint) != 0)
  52. throw new IOException("上传目录包含符号链接,请使用实际目录: " + current);
  53. var entries = Directory.GetFileSystemEntries(current);
  54. if (entries.Length == 0)
  55. {
  56. var relative = current.Length == root.Length ? "" : current.Substring(rootPrefix.Length).Replace('\\', '/') + "/";
  57. files.Add(new S3UploadFile { Key = prefix + "/" + relative });
  58. }
  59. foreach (var path in entries)
  60. {
  61. var attributes = File.GetAttributes(path);
  62. if ((attributes & FileAttributes.ReparsePoint) != 0) throw new IOException("上传目录包含符号链接: " + path);
  63. if ((attributes & FileAttributes.Directory) != 0) { Visit(path); continue; }
  64. long size = new FileInfo(path).Length;
  65. if (size > 5L * 1024 * 1024 * 1024) throw new IOException("单个文件超过 5 GiB,不能直接上传: " + path);
  66. files.Add(new S3UploadFile { LocalPath = path, Key = prefix + "/" + path.Substring(rootPrefix.Length).Replace('\\', '/'), Size = size });
  67. }
  68. }
  69. }
  70. public static string EncodePath(string path) => string.Join("/", path.Split('/').Select(Uri.EscapeDataString));
  71. public static string Authorization(string method, string canonicalPath, string query, IDictionary<string, string> headers,
  72. string payloadHash, string region, S3UploadCredentials credentials, DateTime utc)
  73. {
  74. var sorted = headers.OrderBy(h => h.Key, StringComparer.Ordinal).ToArray();
  75. var signedHeaders = string.Join(";", sorted.Select(h => h.Key));
  76. var canonicalHeaders = string.Concat(sorted.Select(h => h.Key + ":" + h.Value.Trim() + "\n"));
  77. var canonical = method + "\n" + canonicalPath + "\n" + query + "\n" + canonicalHeaders + "\n" + signedHeaders + "\n" + payloadHash;
  78. var date = utc.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
  79. var scope = date + "/" + region + "/s3/aws4_request";
  80. var toSign = "AWS4-HMAC-SHA256\n" + utc.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture) + "\n" + scope + "\n" + Hash(Encoding.UTF8.GetBytes(canonical));
  81. var key = Hmac(Hmac(Hmac(Hmac(Encoding.UTF8.GetBytes("AWS4" + credentials.SecretKey.Trim()), date), region), "s3"), "aws4_request");
  82. return "AWS4-HMAC-SHA256 Credential=" + credentials.AccessKey.Trim() + "/" + scope + ", SignedHeaders=" + signedHeaders + ", Signature=" + Hex(Hmac(key, toSign));
  83. }
  84. public static async Task UploadAsync(IReadOnlyList<S3UploadFile> files, string bucket, string region,
  85. S3UploadCredentials credentials, Action<int, string, long, long> progress, CancellationToken cancellationToken, HttpMessageHandler transport = null)
  86. {
  87. S3UploadSettings.ValidateDestination(bucket, region);
  88. S3UploadSettings.ValidateCredentials(credentials);
  89. using var handler = transport ?? new HttpClientHandler { AllowAutoRedirect = false };
  90. using var client = new HttpClient(handler) { Timeout = Timeout.InfiniteTimeSpan };
  91. long total = files.Sum(f => f.Size), completed = 0;
  92. for (int index = 0; index < files.Count; index++)
  93. {
  94. cancellationToken.ThrowIfCancellationRequested();
  95. var file = files[index];
  96. progress?.Invoke(index, file.Key, completed, total);
  97. for (int attempt = 0; ; attempt++)
  98. {
  99. try
  100. {
  101. using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
  102. timeout.CancelAfter(TimeSpan.FromMinutes(30));
  103. using Stream stream = file.LocalPath == null ? new MemoryStream() : new FileStream(file.LocalPath, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, true);
  104. if (stream.Length != file.Size) throw new IOException("文件在上传前发生改变,请重新选择目录: " + file.Key);
  105. var payloadHash = await HashAsync(stream, timeout.Token).ConfigureAwait(false);
  106. stream.Position = 0;
  107. var host = "s3." + region + ".amazonaws.com";
  108. var path = "/" + bucket + "/" + EncodePath(file.Key);
  109. var now = DateTime.UtcNow;
  110. var headers = new Dictionary<string, string>
  111. {
  112. { "host", host }, { "x-amz-content-sha256", payloadHash },
  113. { "x-amz-date", now.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture) }
  114. };
  115. if (!string.IsNullOrWhiteSpace(credentials.SessionToken)) headers.Add("x-amz-security-token", credentials.SessionToken.Trim());
  116. using var request = new HttpRequestMessage(HttpMethod.Put, "https://" + host + path);
  117. request.Content = new ProgressContent(stream, bytes => progress?.Invoke(index, file.Key, completed + bytes, total), timeout.Token);
  118. request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(file.Key.EndsWith(".json", StringComparison.OrdinalIgnoreCase) ? "application/json" : "application/octet-stream");
  119. request.Headers.TryAddWithoutValidation("Cache-Control", file.IsManifest ? "no-cache, max-age=0, must-revalidate" : "no-cache");
  120. foreach (var header in headers) request.Headers.TryAddWithoutValidation(header.Key, header.Value);
  121. request.Headers.TryAddWithoutValidation("Authorization", Authorization("PUT", path, "", headers, payloadHash, region, credentials, now));
  122. using var response = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead, timeout.Token).ConfigureAwait(false);
  123. if (!response.IsSuccessStatusCode)
  124. {
  125. if (attempt < 2 && ((int)response.StatusCode >= 500 || (int)response.StatusCode == 429))
  126. { await Task.Delay(1000 * (attempt + 1), cancellationToken).ConfigureAwait(false); continue; }
  127. var code = "Unknown";
  128. try { code = XDocument.Parse(await response.Content.ReadAsStringAsync().ConfigureAwait(false)).Root?.Element("Code")?.Value ?? code; }
  129. catch (System.Xml.XmlException) { }
  130. if (!System.Text.RegularExpressions.Regex.IsMatch(code, @"\A[A-Za-z0-9]+\z")) code = "Unknown";
  131. throw new IOException("S3 上传失败: HTTP " + (int)response.StatusCode + " / " + code + " / " + file.Key);
  132. }
  133. break;
  134. }
  135. catch (HttpRequestException) when (attempt < 2)
  136. { await Task.Delay(1000 * (attempt + 1), cancellationToken).ConfigureAwait(false); }
  137. }
  138. completed += file.Size;
  139. progress?.Invoke(index + 1, file.Key, completed, total);
  140. }
  141. }
  142. static async Task<string> HashAsync(Stream stream, CancellationToken token)
  143. {
  144. using var sha = SHA256.Create();
  145. var buffer = new byte[81920];
  146. int count;
  147. while ((count = await stream.ReadAsync(buffer, 0, buffer.Length, token).ConfigureAwait(false)) > 0)
  148. sha.TransformBlock(buffer, 0, count, buffer, 0);
  149. sha.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
  150. return Hex(sha.Hash);
  151. }
  152. public static string Hash(byte[] bytes) { using var sha = SHA256.Create(); return Hex(sha.ComputeHash(bytes)); }
  153. static string Hex(byte[] bytes) => BitConverter.ToString(bytes).Replace("-", "").ToLowerInvariant();
  154. static byte[] Hmac(byte[] key, string text) { using var hmac = new HMACSHA256(key); return hmac.ComputeHash(Encoding.UTF8.GetBytes(text)); }
  155. sealed class ProgressContent : HttpContent
  156. {
  157. readonly Stream source;
  158. readonly Action<long> progress;
  159. readonly CancellationToken token;
  160. public ProgressContent(Stream source, Action<long> progress, CancellationToken token)
  161. { this.source = source; this.progress = progress; this.token = token; }
  162. protected override bool TryComputeLength(out long length) { length = source.Length; return true; }
  163. protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
  164. {
  165. var buffer = new byte[81920];
  166. int count; long sent = 0;
  167. while ((count = await source.ReadAsync(buffer, 0, buffer.Length, token).ConfigureAwait(false)) > 0)
  168. {
  169. await stream.WriteAsync(buffer, 0, count, token).ConfigureAwait(false);
  170. sent += count; progress?.Invoke(sent);
  171. }
  172. }
  173. }
  174. }