using System.Buffers; using System.Globalization; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Security.Cryptography; namespace Chronos.App.About; /// A downloaded update was refused: the release lacks a setup or checksum line, or the bytes do not match. public sealed class UpdateVerificationException(string message) : Exception(message); /// /// "Download" of the update notice (BRIEF §18, P1): fetches the package of the latest release that upgrades this copy /// (the setup, or the portable zip for a portable copy) into a temporary folder and keeps it only when its SHA-256 /// equals the line for it in the release's SHA256SUMS. BRIEF §8.6 does not list starting an installer among the /// OS actions Chronos may perform, so callers show the verified file in Explorer and the user runs or unpacks it. An /// interrupted download resumes from its partial file; a transfer that stalls fails after /// instead of hanging. /// public static class UpdateDownload { public const string ChecksumsName = "SHA256SUMS"; /// A transfer that delivers no byte for this long fails (and can be resumed). public static readonly TimeSpan IdleTimeout = TimeSpan.FromSeconds(60); private const string PartSuffix = ".part"; private const int MaxChecksumsBytes = 64 * 1024; private static readonly SearchValues Hex = SearchValues.Create("0123456789abcdefABCDEF"); /// /// The file that upgrades this copy: the desktop setup ("Chronos-Setup-1.2.3.exe", not the Uploader's) or, for a /// portable copy, the portable zip ("Chronos-win-x64-portable-1.2.3.zip"); null when the release has none. /// public static ReleaseAsset? Package(ReleaseInfo release, bool portable) { var (prefix, extension) = portable ? ("Chronos-win-x64-portable-", ".zip") : ("Chronos-Setup-", ".exe"); return release.Assets.FirstOrDefault(a => a.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && a.Name.EndsWith(extension, StringComparison.OrdinalIgnoreCase) && a.Name == Path.GetFileName(a.Name)); } public static ReleaseAsset? Checksums(ReleaseInfo release) => release.Assets.FirstOrDefault(a => a.Name == ChecksumsName); /// The release carries both the package for this copy and SHA256SUMS; otherwise only its page can be opened. public static bool CanDownload(ReleaseInfo release, bool portable) => Package(release, portable) is not null && Checksums(release) is not null; /// %TEMP%\Chronos\updates: one folder per release below it, all owned by Chronos. public static string Root(string tempPath) => Path.Combine(tempPath, "Chronos", "updates"); /// The folder of one release below , named after its tag. public static string Folder(string root, ReleaseInfo release) => Path.Combine(root, string.Concat(release.Tag.Select(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '-' ? c : '_'))); /// /// File name → lower-case hex SHA-256 from sha256sum output (hash name or hash *name); lines /// that are not a 64-digit hash followed by a name are ignored. /// public static Dictionary ParseChecksums(string text) { var sums = new Dictionary(StringComparer.Ordinal); foreach (var raw in text.Split('\n')) { var line = raw.TrimEnd('\r'); if (line.Length < 66 || line[64] != ' ' || line.AsSpan(0, 64).ContainsAnyExcept(Hex)) continue; var name = line[65..]; if (name.StartsWith(' ') || name.StartsWith('*')) name = name[1..]; if (name.Length > 0) sums[name] = line[..64].ToLowerInvariant(); } return sums; } /// /// Downloads the of for this copy into its under /// , verifies it against SHA256SUMS and returns its path. A verified copy already there /// is reused; an interrupted or cancelled transfer keeps its partial file for the next attempt; bytes that do not /// verify are deleted. After a verified download the folders of other releases under are removed. /// /// The release cannot be verified or the bytes do not match. /// A request failed. /// No byte arrived for . /// The transfer ended early or the file could not be written. public static async Task DownloadAsync(HttpClient http, ReleaseInfo release, bool portable, string root, string userAgentVersion, IProgress? progress, TimeSpan idleTimeout, CancellationToken ct) { var package = Package(release, portable) ?? throw new UpdateVerificationException($"Release {release.Tag} has no {(portable ? "portable zip" : "Chronos setup")}."); var checksums = Checksums(release) ?? throw new UpdateVerificationException($"Release {release.Tag} has no {ChecksumsName}."); var text = await WhileReceivingAsync(idle => ReadChecksumsAsync(http, checksums, userAgentVersion, idle.Token), idleTimeout, ct).ConfigureAwait(false); var expected = ParseChecksums(text).GetValueOrDefault(package.Name) ?? throw new UpdateVerificationException($"{ChecksumsName} of {release.Tag} has no line for {package.Name}."); var folder = Folder(root, release); Directory.CreateDirectory(folder); var target = Path.Combine(folder, package.Name); if (File.Exists(target) && await HashFileAsync(target, ct).ConfigureAwait(false) == expected) { progress?.Report(1); return target; } var part = target + PartSuffix; var actual = await WhileReceivingAsync(idle => DownloadToAsync(http, package, part, userAgentVersion, progress, idle, idleTimeout), idleTimeout, ct) .ConfigureAwait(false); if (actual != expected) { DeleteQuietly(part); throw new UpdateVerificationException($"{package.Name}: SHA-256 {actual} does not match {expected} in {ChecksumsName}."); } File.Move(part, target, overwrite: true); RemoveOtherReleases(root, folder); return target; } /// /// Runs one network phase under a token that fires when nothing arrives for (the phase /// re-arms it on every read) and reports that as a ; the caller's cancellation stays a cancellation. /// private static async Task WhileReceivingAsync(Func> phase, TimeSpan idleTimeout, CancellationToken ct) { using var idle = CancellationTokenSource.CreateLinkedTokenSource(ct); idle.CancelAfter(idleTimeout); try { return await phase(idle).ConfigureAwait(false); } catch (OperationCanceledException) when (idle.IsCancellationRequested && !ct.IsCancellationRequested) { throw new TimeoutException(string.Create(CultureInfo.InvariantCulture, $"No data received for {idleTimeout.TotalSeconds:0} s.")); } } private static async Task ReadChecksumsAsync(HttpClient http, ReleaseAsset asset, string userAgentVersion, CancellationToken ct) { using var response = await SendAsync(http, asset, userAgentVersion, 0, ct).ConfigureAwait(false); if (response.Content.Headers.ContentLength > MaxChecksumsBytes) throw new UpdateVerificationException($"{ChecksumsName} is too large."); var bytes = await response.Content.ReadAsByteArrayAsync(ct).ConfigureAwait(false); if (bytes.Length > MaxChecksumsBytes) throw new UpdateVerificationException($"{ChecksumsName} is too large."); return System.Text.Encoding.UTF8.GetString(bytes); } /// /// Streams the asset into , continuing an existing partial file when the server honours the /// range request, and returns the SHA-256 of the whole file. Refuses more bytes than the release announced and /// fails with an (partial file kept) when the transfer ends before the announced size. /// private static async Task DownloadToAsync(HttpClient http, ReleaseAsset asset, string path, string userAgentVersion, IProgress? progress, CancellationTokenSource idle, TimeSpan idleTimeout) { var ct = idle.Token; using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); var buffer = new byte[1 << 16]; // Resume only with a known size: a partial file of an unknown total cannot be checked against it. var offset = File.Exists(path) ? new FileInfo(path).Length : 0; if (asset.Size <= 0 || offset > asset.Size) offset = 0; if (offset > 0 && offset == asset.Size) return await HashFileAsync(path, ct).ConfigureAwait(false); using var response = await SendAsync(http, asset, userAgentVersion, offset, ct).ConfigureAwait(false); var resumed = offset > 0 && response.StatusCode == HttpStatusCode.PartialContent && response.Content.Headers.ContentRange?.From == offset; await using var output = new FileStream(path, resumed ? FileMode.Open : FileMode.Create, FileAccess.ReadWrite, FileShare.None, 1 << 16, FileOptions.Asynchronous); long total = 0; if (resumed) { int kept; while (total < offset && (kept = await output.ReadAsync(buffer.AsMemory(0, (int)Math.Min(buffer.Length, offset - total)), ct).ConfigureAwait(false)) > 0) { hash.AppendData(buffer, 0, kept); total += kept; } output.SetLength(total); } await using var input = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false); int read; while ((read = await input.ReadAsync(buffer, ct).ConfigureAwait(false)) > 0) { idle.CancelAfter(idleTimeout); total += read; if (asset.Size > 0 && total > asset.Size) { await output.DisposeAsync().ConfigureAwait(false); DeleteQuietly(path); throw new UpdateVerificationException($"{asset.Name} is larger than the release announced."); } hash.AppendData(buffer, 0, read); await output.WriteAsync(buffer.AsMemory(0, read), ct).ConfigureAwait(false); if (asset.Size > 0) progress?.Report((double)total / asset.Size); } await output.FlushAsync(ct).ConfigureAwait(false); if (asset.Size > 0 && total < asset.Size) throw new IOException(string.Create(CultureInfo.InvariantCulture, $"{asset.Name}: the transfer ended after {total} of {asset.Size} bytes.")); return Convert.ToHexStringLower(hash.GetHashAndReset()); } private static async Task SendAsync(HttpClient http, ReleaseAsset asset, string userAgentVersion, long offset, CancellationToken ct) { using var request = new HttpRequestMessage(HttpMethod.Get, asset.DownloadUrl); request.Headers.UserAgent.Add(new ProductInfoHeaderValue("Chronos", userAgentVersion)); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream")); if (offset > 0) request.Headers.Range = new RangeHeaderValue(offset, null); var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); try { response.EnsureSuccessStatusCode(); return response; } catch { response.Dispose(); throw; } } /// Drops the folders of other (older) releases: only the verified setup is worth keeping. private static void RemoveOtherReleases(string root, string keep) { foreach (var folder in Directory.EnumerateDirectories(root)) { if (string.Equals(Path.GetFullPath(folder), Path.GetFullPath(keep), StringComparison.OrdinalIgnoreCase)) continue; try { Directory.Delete(folder, recursive: true); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { // A setup still open (running, scanned) stays until the next verified download. } } } private static void DeleteQuietly(string path) { try { File.Delete(path); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { // A scanner may hold the file; the next download overwrites it. } } private static async Task HashFileAsync(string path, CancellationToken ct) { await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16, FileOptions.Asynchronous | FileOptions.SequentialScan); return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false)); } }