| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184 |
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Security.Cryptography;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Xml.Linq;
- public sealed class S3UploadFile
- {
- public string LocalPath;
- public string Key;
- public long Size;
- public bool IsManifest => Path.GetFileName(Key).Equals("manifest.json", StringComparison.OrdinalIgnoreCase)
- || Path.GetFileName(Key).Equals("manifest_hot.json", StringComparison.OrdinalIgnoreCase);
- }
- public static class S3ResourceUploader
- {
- public static string TargetPrefix(string downloadUrl)
- {
- if (string.IsNullOrWhiteSpace(downloadUrl))
- throw new ArgumentException("请先填写 DownloadUrl,再上传资源。");
- if (!Uri.TryCreate(downloadUrl, UriKind.Absolute, out var uri) || (uri.Scheme != "https" && uri.Scheme != "http"))
- throw new ArgumentException("DownloadUrl 必须是 HTTP(S) 地址。");
- var segments = uri.AbsolutePath.Trim('/').Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).ToList();
- if (segments.Count > 0 && segments.Last().EndsWith(".json", StringComparison.OrdinalIgnoreCase)) segments.RemoveAt(segments.Count - 1);
- if (segments.Count == 0) throw new ArgumentException("DownloadUrl 必须包含上传目标目录,不能是域名根路径。");
- var prefix = Uri.UnescapeDataString(segments.Last());
- if (prefix == "." || prefix == ".." || prefix.Any(c => c == '/' || c == '\\' || char.IsControl(c)))
- throw new ArgumentException("DownloadUrl 最后一级目录不合法。");
- return prefix;
- }
- public static List<S3UploadFile> CreatePlan(string directory, string prefix)
- {
- var root = Path.GetFullPath(directory).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
- if (root.Length == 0 || root.EndsWith(":")) root += Path.DirectorySeparatorChar;
- var rootPrefix = root.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
- if (!Directory.Exists(root)) throw new DirectoryNotFoundException("上传目录不存在。");
- var files = new List<S3UploadFile>();
- Visit(root);
- foreach (var file in files)
- if (Encoding.UTF8.GetByteCount(file.Key) > 1024 || file.Key.Contains("\\") || file.Key.Any(char.IsControl) || file.Key.Split('/').Any(p => p == "." || p == ".."))
- throw new IOException("S3 对象路径不合法或超过 1024 字节: " + file.Key);
- return files.OrderBy(f => f.IsManifest ? 1 : 0).ThenBy(f => f.Key, StringComparer.Ordinal).ToList();
- void Visit(string current)
- {
- if ((File.GetAttributes(current) & FileAttributes.ReparsePoint) != 0)
- throw new IOException("上传目录包含符号链接,请使用实际目录: " + current);
- var entries = Directory.GetFileSystemEntries(current);
- if (entries.Length == 0)
- {
- var relative = current.Length == root.Length ? "" : current.Substring(rootPrefix.Length).Replace('\\', '/') + "/";
- files.Add(new S3UploadFile { Key = prefix + "/" + relative });
- }
- foreach (var path in entries)
- {
- var attributes = File.GetAttributes(path);
- if ((attributes & FileAttributes.ReparsePoint) != 0) throw new IOException("上传目录包含符号链接: " + path);
- if ((attributes & FileAttributes.Directory) != 0) { Visit(path); continue; }
- long size = new FileInfo(path).Length;
- if (size > 5L * 1024 * 1024 * 1024) throw new IOException("单个文件超过 5 GiB,不能直接上传: " + path);
- files.Add(new S3UploadFile { LocalPath = path, Key = prefix + "/" + path.Substring(rootPrefix.Length).Replace('\\', '/'), Size = size });
- }
- }
- }
- public static string EncodePath(string path) => string.Join("/", path.Split('/').Select(Uri.EscapeDataString));
- public static string Authorization(string method, string canonicalPath, string query, IDictionary<string, string> headers,
- string payloadHash, string region, S3UploadCredentials credentials, DateTime utc)
- {
- var sorted = headers.OrderBy(h => h.Key, StringComparer.Ordinal).ToArray();
- var signedHeaders = string.Join(";", sorted.Select(h => h.Key));
- var canonicalHeaders = string.Concat(sorted.Select(h => h.Key + ":" + h.Value.Trim() + "\n"));
- var canonical = method + "\n" + canonicalPath + "\n" + query + "\n" + canonicalHeaders + "\n" + signedHeaders + "\n" + payloadHash;
- var date = utc.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
- var scope = date + "/" + region + "/s3/aws4_request";
- var toSign = "AWS4-HMAC-SHA256\n" + utc.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture) + "\n" + scope + "\n" + Hash(Encoding.UTF8.GetBytes(canonical));
- var key = Hmac(Hmac(Hmac(Hmac(Encoding.UTF8.GetBytes("AWS4" + credentials.SecretKey.Trim()), date), region), "s3"), "aws4_request");
- return "AWS4-HMAC-SHA256 Credential=" + credentials.AccessKey.Trim() + "/" + scope + ", SignedHeaders=" + signedHeaders + ", Signature=" + Hex(Hmac(key, toSign));
- }
- public static async Task UploadAsync(IReadOnlyList<S3UploadFile> files, string bucket, string region,
- S3UploadCredentials credentials, Action<int, string, long, long> progress, CancellationToken cancellationToken, HttpMessageHandler transport = null)
- {
- S3UploadSettings.ValidateDestination(bucket, region);
- S3UploadSettings.ValidateCredentials(credentials);
- using var handler = transport ?? new HttpClientHandler { AllowAutoRedirect = false };
- using var client = new HttpClient(handler) { Timeout = Timeout.InfiniteTimeSpan };
- long total = files.Sum(f => f.Size), completed = 0;
- for (int index = 0; index < files.Count; index++)
- {
- cancellationToken.ThrowIfCancellationRequested();
- var file = files[index];
- progress?.Invoke(index, file.Key, completed, total);
- for (int attempt = 0; ; attempt++)
- {
- try
- {
- using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
- timeout.CancelAfter(TimeSpan.FromMinutes(30));
- using Stream stream = file.LocalPath == null ? new MemoryStream() : new FileStream(file.LocalPath, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, true);
- if (stream.Length != file.Size) throw new IOException("文件在上传前发生改变,请重新选择目录: " + file.Key);
- var payloadHash = await HashAsync(stream, timeout.Token).ConfigureAwait(false);
- stream.Position = 0;
- var host = "s3." + region + ".amazonaws.com";
- var path = "/" + bucket + "/" + EncodePath(file.Key);
- var now = DateTime.UtcNow;
- var headers = new Dictionary<string, string>
- {
- { "host", host }, { "x-amz-content-sha256", payloadHash },
- { "x-amz-date", now.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture) }
- };
- if (!string.IsNullOrWhiteSpace(credentials.SessionToken)) headers.Add("x-amz-security-token", credentials.SessionToken.Trim());
- using var request = new HttpRequestMessage(HttpMethod.Put, "https://" + host + path);
- request.Content = new ProgressContent(stream, bytes => progress?.Invoke(index, file.Key, completed + bytes, total), timeout.Token);
- request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(file.Key.EndsWith(".json", StringComparison.OrdinalIgnoreCase) ? "application/json" : "application/octet-stream");
- request.Headers.TryAddWithoutValidation("Cache-Control", file.IsManifest ? "no-cache, max-age=0, must-revalidate" : "no-cache");
- foreach (var header in headers) request.Headers.TryAddWithoutValidation(header.Key, header.Value);
- request.Headers.TryAddWithoutValidation("Authorization", Authorization("PUT", path, "", headers, payloadHash, region, credentials, now));
- using var response = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead, timeout.Token).ConfigureAwait(false);
- if (!response.IsSuccessStatusCode)
- {
- if (attempt < 2 && ((int)response.StatusCode >= 500 || (int)response.StatusCode == 429))
- { await Task.Delay(1000 * (attempt + 1), cancellationToken).ConfigureAwait(false); continue; }
- var code = "Unknown";
- try { code = XDocument.Parse(await response.Content.ReadAsStringAsync().ConfigureAwait(false)).Root?.Element("Code")?.Value ?? code; }
- catch (System.Xml.XmlException) { }
- if (!System.Text.RegularExpressions.Regex.IsMatch(code, @"\A[A-Za-z0-9]+\z")) code = "Unknown";
- throw new IOException("S3 上传失败: HTTP " + (int)response.StatusCode + " / " + code + " / " + file.Key);
- }
- break;
- }
- catch (HttpRequestException) when (attempt < 2)
- { await Task.Delay(1000 * (attempt + 1), cancellationToken).ConfigureAwait(false); }
- }
- completed += file.Size;
- progress?.Invoke(index + 1, file.Key, completed, total);
- }
- }
- static async Task<string> HashAsync(Stream stream, CancellationToken token)
- {
- using var sha = SHA256.Create();
- var buffer = new byte[81920];
- int count;
- while ((count = await stream.ReadAsync(buffer, 0, buffer.Length, token).ConfigureAwait(false)) > 0)
- sha.TransformBlock(buffer, 0, count, buffer, 0);
- sha.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
- return Hex(sha.Hash);
- }
- public static string Hash(byte[] bytes) { using var sha = SHA256.Create(); return Hex(sha.ComputeHash(bytes)); }
- static string Hex(byte[] bytes) => BitConverter.ToString(bytes).Replace("-", "").ToLowerInvariant();
- static byte[] Hmac(byte[] key, string text) { using var hmac = new HMACSHA256(key); return hmac.ComputeHash(Encoding.UTF8.GetBytes(text)); }
- sealed class ProgressContent : HttpContent
- {
- readonly Stream source;
- readonly Action<long> progress;
- readonly CancellationToken token;
- public ProgressContent(Stream source, Action<long> progress, CancellationToken token)
- { this.source = source; this.progress = progress; this.token = token; }
- protected override bool TryComputeLength(out long length) { length = source.Length; return true; }
- protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
- {
- var buffer = new byte[81920];
- int count; long sent = 0;
- while ((count = await source.ReadAsync(buffer, 0, buffer.Length, token).ConfigureAwait(false)) > 0)
- {
- await stream.WriteAsync(buffer, 0, count, token).ConfigureAwait(false);
- sent += count; progress?.Invoke(sent);
- }
- }
- }
- }
|