using System.Buffers; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Security.Cryptography; namespace Titano.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 desktop setup of the latest release 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 Titano may perform, so callers show the verified file in /// Explorer and the user runs it. /// public static class UpdateDownload { public const string ChecksumsName = "SHA256SUMS"; private const int MaxChecksumsBytes = 64 * 1024; private static readonly SearchValues Hex = SearchValues.Create("0123456789abcdefABCDEF"); /// The desktop setup ("Titano-Setup-1.2.3.exe"), not the Uploader's. public static ReleaseAsset? Installer(ReleaseInfo release) => release.Assets.FirstOrDefault(a => a.Name.StartsWith("Titano-Setup-", StringComparison.OrdinalIgnoreCase) && a.Name.EndsWith(".exe", 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 a setup and SHA256SUMS; otherwise only its page can be opened. public static bool CanDownload(ReleaseInfo release) => Installer(release) is not null && Checksums(release) is not null; /// %TEMP%\Titano\updates\<tag> under . public static string Folder(string tempRoot, ReleaseInfo release) => Path.Combine(tempRoot, "Titano", "updates", 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 setup of into , verifies it against /// SHA256SUMS and returns its path. A verified copy already there is reused; a partial or mismatching /// download is deleted. /// /// The release cannot be verified or the bytes do not match. /// A request failed. public static async Task DownloadAsync(HttpClient http, ReleaseInfo release, string folder, string userAgentVersion, IProgress? progress, CancellationToken ct) { var installer = Installer(release) ?? throw new UpdateVerificationException($"Release {release.Tag} has no Titano setup."); var checksums = Checksums(release) ?? throw new UpdateVerificationException($"Release {release.Tag} has no {ChecksumsName}."); var expected = ParseChecksums(await ReadChecksumsAsync(http, checksums, userAgentVersion, ct).ConfigureAwait(false)).GetValueOrDefault(installer.Name) ?? throw new UpdateVerificationException($"{ChecksumsName} of {release.Tag} has no line for {installer.Name}."); Directory.CreateDirectory(folder); var target = Path.Combine(folder, installer.Name); if (File.Exists(target) && await HashFileAsync(target, ct).ConfigureAwait(false) == expected) { progress?.Report(1); return target; } var part = target + ".part"; try { var actual = await DownloadToAsync(http, installer, part, userAgentVersion, progress, ct).ConfigureAwait(false); if (actual != expected) throw new UpdateVerificationException($"{installer.Name}: SHA-256 {actual} does not match {expected} in {ChecksumsName}."); File.Move(part, target, overwrite: true); return target; } finally { DeleteQuietly(part); } } private static async Task ReadChecksumsAsync(HttpClient http, ReleaseAsset asset, string userAgentVersion, CancellationToken ct) { using var response = await SendAsync(http, asset, userAgentVersion, 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 , hashing as it goes; refuses more bytes than the release announced. private static async Task DownloadToAsync(HttpClient http, ReleaseAsset asset, string path, string userAgentVersion, IProgress? progress, CancellationToken ct) { using var response = await SendAsync(http, asset, userAgentVersion, ct).ConfigureAwait(false); var length = asset.Size > 0 ? asset.Size : response.Content.Headers.ContentLength ?? -1; await using var input = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false); await using var output = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16, FileOptions.Asynchronous); using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); var buffer = new byte[1 << 16]; long total = 0; int read; while ((read = await input.ReadAsync(buffer, ct).ConfigureAwait(false)) > 0) { total += read; if (asset.Size > 0 && total > asset.Size) 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 (length > 0) progress?.Report(Math.Min(1.0, (double)total / length)); } await output.FlushAsync(ct).ConfigureAwait(false); return Convert.ToHexStringLower(hash.GetHashAndReset()); } private static async Task SendAsync(HttpClient http, ReleaseAsset asset, string userAgentVersion, CancellationToken ct) { using var request = new HttpRequestMessage(HttpMethod.Get, asset.DownloadUrl); request.Headers.UserAgent.Add(new ProductInfoHeaderValue("Titano", userAgentVersion)); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream")); var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); try { response.EnsureSuccessStatusCode(); return response; } catch { response.Dispose(); throw; } } private static void DeleteQuietly(string path) { try { File.Delete(path); } catch (IOException) { // A scanner may hold the partial file; %TEMP% cleanup removes it later. } catch (UnauthorizedAccessException) { } } 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)); } }