diff --git a/i18n/en/About.resx b/i18n/en/About.resx index ce8aea99..1dc68f3f 100644 --- a/i18n/en/About.resx +++ b/i18n/en/About.resx @@ -23,6 +23,11 @@ Checking… Up to date Download + Download failed + Downloading {0:P0} Check failed + Download not verified + Titano {0} downloaded + Show setup Updates diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index 7ca6cbe4..a815b5e5 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -6,11 +6,12 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Ask the public releases page for a newer version · a few seconds Zip the logs and an environment report into a folder you choose; settings and passwords are not included - Open the release page in the browser + Download the setup, check it against the release's SHA-256 list and show it in Explorer · tens of MB Open the licence in the browser Open the folder with database, settings and logs Open the public releases page in the browser Every language but English is machine-translated; propose a better wording on the public issue tracker + Show the verified setup in Explorer; close Titano and run it to upgrade. Archive and settings are kept Titano uses no third-party code: everything beyond .NET and Windows is written in-house Dismiss Open the folder with the log files diff --git a/i18n/it/About.it.resx b/i18n/it/About.it.resx index 2370ca1e..2f871e07 100644 --- a/i18n/it/About.it.resx +++ b/i18n/it/About.it.resx @@ -23,6 +23,11 @@ Verifica in corso… Aggiornato Scarica + Download non riuscito + Download in corso {0:P0} Verifica non riuscita + Download non verificato + Titano {0} scaricato + Mostra installer Aggiornamenti diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index c81ad08f..1eba743f 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -6,11 +6,12 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Chiede alla pagina pubblica delle versioni se ne esiste una più recente · pochi secondi Comprime i log e un rapporto sull'ambiente in una cartella a tua scelta; impostazioni e password non sono incluse - Apre la pagina della versione nel browser + Scarica l'installer, lo confronta con l'elenco SHA-256 della versione e lo mostra in Esplora file · decine di MB Apre la licenza nel browser Apri la cartella con database, impostazioni e log Apri la pagina pubblica delle versioni nel browser Tutte le lingue tranne l'inglese sono tradotte automaticamente; proponi una formulazione migliore nel tracker pubblico + Mostra in Esplora file l'installer verificato; chiudi Titano ed eseguilo per aggiornare. Archivio e impostazioni restano invariati Titano non usa codice di terze parti: tutto ciò che va oltre .NET e Windows è scritto internamente Chiudi Apri la cartella dei file di log diff --git a/src/Titano.App/About/UpdateCheck.cs b/src/Titano.App/About/UpdateCheck.cs index 8434cb88..0ad76278 100644 --- a/src/Titano.App/About/UpdateCheck.cs +++ b/src/Titano.App/About/UpdateCheck.cs @@ -4,8 +4,14 @@ using System.Text.Json; namespace Titano.App.About; -/// The newest public release (BRIEF §18). -public sealed record ReleaseInfo(Version Version, string Tag, string PageUrl); +/// The newest public release (BRIEF §18) with its downloadable files. +public sealed record ReleaseInfo(Version Version, string Tag, string PageUrl) +{ + public IReadOnlyList Assets { get; init; } = []; +} + +/// One file attached to a release. +public sealed record ReleaseAsset(string Name, string DownloadUrl, long Size); /// /// Update check against the GitHub Releases API of the public releases repository (BRIEF §18, §19.4): reads the @@ -26,7 +32,8 @@ public static class UpdateCheck return new Version(version.Major, version.Minor, Math.Max(0, version.Build)); } - /// The release described by a releases/latest response; null for drafts, pre-releases or unparsable tags. + /// The release described by a releases/latest response; null for drafts, pre-releases or unparsable tags. + /// Assets without an https download link are left out. public static ReleaseInfo? Parse(string json) { using var document = JsonDocument.Parse(json); @@ -37,7 +44,7 @@ public static class UpdateCheck var url = root.TryGetProperty("html_url", out var u) && u.ValueKind == JsonValueKind.String ? u.GetString() : null; var version = ParseVersion(tag); if (version is null || tag is null || url is null || !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) return null; - return new ReleaseInfo(version, tag, url); + return new ReleaseInfo(version, tag, url) { Assets = ParseAssets(root) }; } /// True when is newer than (build/revision ignored). @@ -68,6 +75,22 @@ public static class UpdateCheck } } + private static List ParseAssets(JsonElement root) + { + var assets = new List(); + if (!root.TryGetProperty("assets", out var list) || list.ValueKind != JsonValueKind.Array) return assets; + foreach (var a in list.EnumerateArray()) + { + if (a.ValueKind != JsonValueKind.Object) continue; + var name = a.TryGetProperty("name", out var n) && n.ValueKind == JsonValueKind.String ? n.GetString() : null; + var link = a.TryGetProperty("browser_download_url", out var d) && d.ValueKind == JsonValueKind.String ? d.GetString() : null; + var size = a.TryGetProperty("size", out var z) && z.ValueKind == JsonValueKind.Number && z.TryGetInt64(out var bytes) ? bytes : -1; + if (string.IsNullOrEmpty(name) || link is null || !link.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) continue; + assets.Add(new ReleaseAsset(name, link, size)); + } + return assets; + } + private static bool Flag(JsonElement root, string name) => root.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.True; diff --git a/src/Titano.App/About/UpdateDownload.cs b/src/Titano.App/About/UpdateDownload.cs new file mode 100644 index 00000000..7fade974 --- /dev/null +++ b/src/Titano.App/About/UpdateDownload.cs @@ -0,0 +1,165 @@ +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)); + } +} diff --git a/src/Titano.App/Infrastructure/AppServices.cs b/src/Titano.App/Infrastructure/AppServices.cs index 5ed5098f..d6dc5a8d 100644 --- a/src/Titano.App/Infrastructure/AppServices.cs +++ b/src/Titano.App/Infrastructure/AppServices.cs @@ -38,6 +38,9 @@ public sealed class AppServices : IAsyncDisposable public static readonly TimeSpan ScanInterval = TimeSpan.FromMinutes(10); private static readonly Lazy Http = new(() => new HttpClient { Timeout = TimeSpan.FromSeconds(20) }); + + /// Setups are large: the download is bounded by the caller's cancellation, not a short timeout. + private static readonly Lazy DownloadHttp = new(() => new HttpClient { Timeout = TimeSpan.FromMinutes(30) }); private readonly CancellationTokenSource _stopping = new(); private readonly Dictionary _scans = []; private Task _polling = Task.CompletedTask; @@ -55,6 +58,8 @@ public sealed class AppServices : IAsyncDisposable Server = new ServerSession(settings, saveSettings, new TitanoServerApiFactory(), new DpapiTokenProtector()); Encoders = new MediaFoundationInventory(); CheckForUpdateAsync = ct => UpdateCheck.FetchAsync(Http.Value, ProductLinks.LatestReleaseApi, VersionText, ct); + DownloadUpdateAsync = (release, progress, ct) => + UpdateDownload.DownloadAsync(DownloadHttp.Value, release, UpdateDownload.Folder(Path.GetTempPath(), release), VersionText, progress, ct); } public AppEnvironment Environment { get; } @@ -89,6 +94,9 @@ public sealed class AppServices : IAsyncDisposable /// Latest public release (GitHub Releases API of the releases repository, BRIEF §18). public Func> CheckForUpdateAsync { get; set; } + /// Downloads and verifies the setup of a release (BRIEF §18 P1) and returns its path. + public Func?, CancellationToken, Task> DownloadUpdateAsync { get; set; } + /// The index; null until succeeded. public TitanoDatabase? Database { get; private set; } diff --git a/src/Titano.App/Sections/AboutView.xaml b/src/Titano.App/Sections/AboutView.xaml index 30236370..7b445788 100644 --- a/src/Titano.App/Sections/AboutView.xaml +++ b/src/Titano.App/Sections/AboutView.xaml @@ -57,6 +57,9 @@