Files
Chronos/src/Chronos.App/About/UpdateDownload.cs
T
Alby96andClaude Opus 5.5 f2b58522b9
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-10-23 12:45:18 +02:00

252 lines
13 KiB
C#

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;
/// <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 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 <c>SHA256SUMS</c>. 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 <see cref="IdleTimeout"/>
/// instead of hanging.
/// </summary>
public static class UpdateDownload
{
public const string ChecksumsName = "SHA256SUMS";
/// <summary>A transfer that delivers no byte for this long fails (and can be resumed).</summary>
public static readonly TimeSpan IdleTimeout = TimeSpan.FromSeconds(60);
private const string PartSuffix = ".part";
private const int MaxChecksumsBytes = 64 * 1024;
private static readonly SearchValues<char> Hex = SearchValues.Create("0123456789abcdefABCDEF");
/// <summary>
/// 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.
/// </summary>
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);
/// <summary>The release carries both the package for this copy and <c>SHA256SUMS</c>; otherwise only its page can be opened.</summary>
public static bool CanDownload(ReleaseInfo release, bool portable) => Package(release, portable) is not null && Checksums(release) is not null;
/// <summary><c>%TEMP%\Chronos\updates</c>: one folder per release below it, all owned by Chronos.</summary>
public static string Root(string tempPath) => Path.Combine(tempPath, "Chronos", "updates");
/// <summary>The folder of one release below <paramref name="root"/>, named after its tag.</summary>
public static string Folder(string root, ReleaseInfo release) =>
Path.Combine(root, 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 <see cref="Package"/> of <paramref name="release"/> for this copy into its <see cref="Folder"/> under
/// <paramref name="root"/>, verifies it against <c>SHA256SUMS</c> 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 <paramref name="root"/> are removed.
/// </summary>
/// <exception cref="UpdateVerificationException">The release cannot be verified or the bytes do not match.</exception>
/// <exception cref="HttpRequestException">A request failed.</exception>
/// <exception cref="TimeoutException">No byte arrived for <paramref name="idleTimeout"/>.</exception>
/// <exception cref="IOException">The transfer ended early or the file could not be written.</exception>
public static async Task<string> DownloadAsync(HttpClient http, ReleaseInfo release, bool portable, string root, string userAgentVersion,
IProgress<double>? 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;
}
/// <summary>
/// Runs one network phase under a token that fires when nothing arrives for <paramref name="idleTimeout"/> (the phase
/// re-arms it on every read) and reports that as a <see cref="TimeoutException"/>; the caller's cancellation stays a cancellation.
/// </summary>
private static async Task<T> WhileReceivingAsync<T>(Func<CancellationTokenSource, Task<T>> 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<string> 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);
}
/// <summary>
/// Streams the asset into <paramref name="path"/>, 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 <see cref="IOException"/> (partial file kept) when the transfer ends before the announced size.
/// </summary>
private static async Task<string> DownloadToAsync(HttpClient http, ReleaseAsset asset, string path, string userAgentVersion, IProgress<double>? 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<HttpResponseMessage> 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;
}
}
/// <summary>Drops the folders of other (older) releases: only the verified setup is worth keeping.</summary>
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<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));
}
}