Download now fetches the desktop setup of the latest release into %TEMP%\Titano\updates\<tag>, keeps it only when its SHA-256 matches the release's SHA256SUMS line, and shows it in Explorer. BRIEF 8.6 does not list starting an installer among the allowed shell actions, so the user runs it. A release without a setup or SHA256SUMS still opens its page; capture runs never download. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
166 lines
8.6 KiB
C#
166 lines
8.6 KiB
C#
using System.Buffers;
|
|
using System.IO;
|
|
using System.Net.Http;
|
|
using System.Net.Http.Headers;
|
|
using System.Security.Cryptography;
|
|
|
|
namespace Titano.App.About;
|
|
|
|
/// <summary>A downloaded update was refused: the release lacks a setup or checksum line, or the bytes do not match.</summary>
|
|
public sealed class UpdateVerificationException(string message) : Exception(message);
|
|
|
|
/// <summary>
|
|
/// "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 <c>SHA256SUMS</c>. 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.
|
|
/// </summary>
|
|
public static class UpdateDownload
|
|
{
|
|
public const string ChecksumsName = "SHA256SUMS";
|
|
private const int MaxChecksumsBytes = 64 * 1024;
|
|
private static readonly SearchValues<char> Hex = SearchValues.Create("0123456789abcdefABCDEF");
|
|
|
|
/// <summary>The desktop setup ("Titano-Setup-1.2.3.exe"), not the Uploader's.</summary>
|
|
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);
|
|
|
|
/// <summary>The release carries both a setup and <c>SHA256SUMS</c>; otherwise only its page can be opened.</summary>
|
|
public static bool CanDownload(ReleaseInfo release) => Installer(release) is not null && Checksums(release) is not null;
|
|
|
|
/// <summary><c>%TEMP%\Titano\updates\<tag></c> under <paramref name="tempRoot"/>.</summary>
|
|
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 : '_')));
|
|
|
|
/// <summary>
|
|
/// File name → lower-case hex SHA-256 from <c>sha256sum</c> output (<c>hash name</c> or <c>hash *name</c>); lines
|
|
/// that are not a 64-digit hash followed by a name are ignored.
|
|
/// </summary>
|
|
public static Dictionary<string, string> ParseChecksums(string text)
|
|
{
|
|
var sums = new Dictionary<string, string>(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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Downloads the setup of <paramref name="release"/> into <paramref name="folder"/>, verifies it against
|
|
/// <c>SHA256SUMS</c> and returns its path. A verified copy already there is reused; a partial or mismatching
|
|
/// download is deleted.
|
|
/// </summary>
|
|
/// <exception cref="UpdateVerificationException">The release cannot be verified or the bytes do not match.</exception>
|
|
/// <exception cref="HttpRequestException">A request failed.</exception>
|
|
public static async Task<string> DownloadAsync(HttpClient http, ReleaseInfo release, string folder, string userAgentVersion, IProgress<double>? 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<string> 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);
|
|
}
|
|
|
|
/// <summary>Streams the asset into <paramref name="path"/>, hashing as it goes; refuses more bytes than the release announced.</summary>
|
|
private static async Task<string> DownloadToAsync(HttpClient http, ReleaseAsset asset, string path, string userAgentVersion, IProgress<double>? 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<HttpResponseMessage> 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<string> 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));
|
|
}
|
|
}
|