From d79ab1e41bffa65f5d7a59040a6ebf7407c4f5ee Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:56:37 +0000 Subject: [PATCH 1/9] feat(packaging): add TPK1 self-extracting payload format Installer payload appended to the setup program: JSON manifest (components, files with size/SHA-256/offsets/mtime, shortcuts, file types) plus deflate or stored entries and a 64-byte footer with the manifest hash. The reader finds the footer before an Authenticode table, validates every offset, rejects unsafe paths and bounds inflation by the declared size; the writer is deterministic, deduplicates identical content and strips a signed stub. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Packaging/PayloadException.cs | 21 ++ src/Titano.Core/Packaging/PayloadFormat.cs | 52 ++++ src/Titano.Core/Packaging/PayloadManifest.cs | 214 ++++++++++++++++ src/Titano.Core/Packaging/PayloadPath.cs | 68 +++++ src/Titano.Core/Packaging/PayloadReader.cs | 235 ++++++++++++++++++ src/Titano.Core/Packaging/PayloadWriter.cs | 225 +++++++++++++++++ src/Titano.Core/Packaging/PeImage.cs | 56 +++++ src/Titano.Core/Packaging/WindowStream.cs | 42 ++++ .../Packaging/PackagingFixture.cs | 130 ++++++++++ .../Packaging/PayloadIntegrityTests.cs | 213 ++++++++++++++++ .../Packaging/PayloadPathTests.cs | 60 +++++ .../Packaging/PayloadRoundTripTests.cs | 172 +++++++++++++ 12 files changed, 1488 insertions(+) create mode 100644 src/Titano.Core/Packaging/PayloadException.cs create mode 100644 src/Titano.Core/Packaging/PayloadFormat.cs create mode 100644 src/Titano.Core/Packaging/PayloadManifest.cs create mode 100644 src/Titano.Core/Packaging/PayloadPath.cs create mode 100644 src/Titano.Core/Packaging/PayloadReader.cs create mode 100644 src/Titano.Core/Packaging/PayloadWriter.cs create mode 100644 src/Titano.Core/Packaging/PeImage.cs create mode 100644 src/Titano.Core/Packaging/WindowStream.cs create mode 100644 tests/Titano.Core.Tests/Packaging/PackagingFixture.cs create mode 100644 tests/Titano.Core.Tests/Packaging/PayloadIntegrityTests.cs create mode 100644 tests/Titano.Core.Tests/Packaging/PayloadPathTests.cs create mode 100644 tests/Titano.Core.Tests/Packaging/PayloadRoundTripTests.cs diff --git a/src/Titano.Core/Packaging/PayloadException.cs b/src/Titano.Core/Packaging/PayloadException.cs new file mode 100644 index 00000000..ebe08039 --- /dev/null +++ b/src/Titano.Core/Packaging/PayloadException.cs @@ -0,0 +1,21 @@ +namespace Titano.Core.Packaging; + +/// Why a TPK1 payload could not be read, written or extracted. +public enum PayloadError +{ + /// The file carries no payload footer: not a packed installer, or its end was cut off. + NotFound, + + /// Footer, manifest or entry data are inconsistent, truncated or fail their SHA-256. + Corrupt, + + /// A path is absolute, escapes the target folder or uses a name Windows cannot store. + UnsafePath, +} + +/// A payload problem with a machine-readable for exit codes and UI messages. +public sealed class PayloadException(PayloadError error, string message, Exception? innerException = null) + : Exception(message, innerException) +{ + public PayloadError Error { get; } = error; +} diff --git a/src/Titano.Core/Packaging/PayloadFormat.cs b/src/Titano.Core/Packaging/PayloadFormat.cs new file mode 100644 index 00000000..a9d8d4f7 --- /dev/null +++ b/src/Titano.Core/Packaging/PayloadFormat.cs @@ -0,0 +1,52 @@ +using System.Buffers.Binary; + +namespace Titano.Core.Packaging; + +/// +/// The TPK1 self-extracting layout: [setup stub][manifest JSON][entry data][zero padding][footer], optionally +/// followed by an Authenticode certificate table that signtool appends when the installer is signed. +/// The footer is 64 bytes, little-endian: magic "TPK1END\0" · payload offset (int64, absolute offset of the +/// manifest) · manifest length (int64) · data length (int64) · SHA-256 of the manifest bytes (32 bytes). +/// Entry offsets in the manifest are relative to the first byte after the manifest. Padding aligns the end of the +/// footer to 8 bytes so a signature can be appended without signtool inserting bytes of its own. +/// +public static class PayloadFormat +{ + public const int FooterLength = 64; + public const int Alignment = 8; + public const int ManifestFormatVersion = 1; + + /// Upper bound for the manifest; a larger value in a footer means corruption. + public const int MaxManifestLength = 64 << 20; + + /// Deflate cannot expand data by more than about 1032:1; larger declared sizes are rejected up front. + public const int MaxDeflateRatio = 1032; + + public static ReadOnlySpan Magic => "TPK1END\0"u8; +} + +/// Decoded TPK1 footer. +internal readonly record struct PayloadFooter(long PayloadOffset, long ManifestLength, long DataLength, byte[] ManifestHash) +{ + public void WriteTo(Span destination) + { + PayloadFormat.Magic.CopyTo(destination); + BinaryPrimitives.WriteInt64LittleEndian(destination[8..], PayloadOffset); + BinaryPrimitives.WriteInt64LittleEndian(destination[16..], ManifestLength); + BinaryPrimitives.WriteInt64LittleEndian(destination[24..], DataLength); + ManifestHash.CopyTo(destination[32..]); + } + + /// Parses a footer; false when the magic does not match. + public static bool TryParse(ReadOnlySpan source, out PayloadFooter footer) + { + footer = default; + if (source.Length < PayloadFormat.FooterLength || !source[..8].SequenceEqual(PayloadFormat.Magic)) return false; + footer = new PayloadFooter( + BinaryPrimitives.ReadInt64LittleEndian(source[8..]), + BinaryPrimitives.ReadInt64LittleEndian(source[16..]), + BinaryPrimitives.ReadInt64LittleEndian(source[24..]), + source.Slice(32, 32).ToArray()); + return true; + } +} diff --git a/src/Titano.Core/Packaging/PayloadManifest.cs b/src/Titano.Core/Packaging/PayloadManifest.cs new file mode 100644 index 00000000..e4b304cc --- /dev/null +++ b/src/Titano.Core/Packaging/PayloadManifest.cs @@ -0,0 +1,214 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.RegularExpressions; + +namespace Titano.Core.Packaging; + +/// How an entry's bytes are stored in the data region. +public enum PayloadCompression +{ + Stored, + Deflate, +} + +/// Describes everything a TPK1 installer carries: product, components, files, shortcuts and file types. +public sealed partial class PayloadManifest +{ + public int FormatVersion { get; init; } = PayloadFormat.ManifestFormatVersion; + public required string Product { get; init; } + public required string Version { get; init; } + public List Components { get; init; } = []; + public List Files { get; init; } = []; + public List Shortcuts { get; init; } = []; + public List Associations { get; init; } = []; + + /// The component with (ordinal, case-insensitive), or null. + public PayloadComponent? FindComponent(string id) => + Components.FirstOrDefault(c => c.Id.Equals(id, StringComparison.OrdinalIgnoreCase)); + + /// + /// Files installed by the given components, one entry per path in manifest order. A path shared by several + /// components (identical content, enforced by ) is listed once. + /// + public IReadOnlyList FilesFor(IEnumerable componentIds) + { + var selected = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var id in componentIds) + { + var component = FindComponent(id) ?? throw new ArgumentException($"Unknown component '{id}'.", nameof(componentIds)); + selected.Add(component.Id); + } + var seen = new HashSet(PayloadPath.Comparer); + var result = new List(); + foreach (var file in Files) + { + if (selected.Contains(file.Component) && seen.Add(file.Path)) result.Add(file); + } + return result; + } + + /// Rejects manifests that are inconsistent with themselves or with a data region of bytes. + public void Validate(long dataLength) + { + if (FormatVersion != PayloadFormat.ManifestFormatVersion) Fail($"unsupported manifest format {FormatVersion}"); + if (!PayloadPath.IsValidSegment(Product) || Product.Length > 100) Fail("invalid product name"); + if (string.IsNullOrWhiteSpace(Version) || Version.Length > 64) Fail("invalid version"); + if (Components.Count == 0) Fail("no components"); + + var componentIds = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var c in Components) + { + if (c is null || !IdentifierRegex().IsMatch(c.Id)) Fail("invalid component id"); + if (!componentIds.Add(c.Id)) Fail($"duplicate component {c.Id}"); + if (string.IsNullOrWhiteSpace(c.DisplayName) || c.DisplayName.Length > 100) Fail($"invalid display name for {c.Id}"); + if (c.EstimatedSize < 0) Fail($"negative size for {c.Id}"); + } + + var perComponent = new HashSet<(string, string)>(); + var byPath = new Dictionary(PayloadPath.Comparer); + foreach (var f in Files) + { + if (f is null) Fail("empty file entry"); + if (!PayloadPath.IsValid(f.Path)) throw new PayloadException(PayloadError.UnsafePath, $"Unsafe payload path '{f.Path}'."); + if (!componentIds.Contains(f.Component)) Fail($"{f.Path} belongs to an unknown component"); + if (!perComponent.Add((f.Component.ToUpperInvariant(), f.Path.ToUpperInvariant()))) Fail($"duplicate file {f.Path}"); + if (f.Size < 0 || f.Offset < 0 || f.Length < 0 || f.Offset > dataLength || f.Length > dataLength - f.Offset) + Fail($"{f.Path} lies outside the data region"); + if (!Sha256Regex().IsMatch(f.Sha256)) Fail($"{f.Path} has no valid SHA-256"); + switch (f.Compression) + { + case PayloadCompression.Stored when f.Length != f.Size: + Fail($"{f.Path}: stored length differs from size"); + break; + case PayloadCompression.Deflate when f.Size / PayloadFormat.MaxDeflateRatio > f.Length: + Fail($"{f.Path}: declared size exceeds the deflate limit"); + break; + case PayloadCompression.Stored or PayloadCompression.Deflate: + break; + default: + Fail($"{f.Path}: unknown compression"); + break; + } + if (byPath.TryGetValue(f.Path, out var other) && (other.Size != f.Size || !other.Sha256.Equals(f.Sha256, StringComparison.Ordinal))) + Fail($"{f.Path} differs between components {other.Component} and {f.Component}"); + byPath.TryAdd(f.Path, f); + } + + foreach (var s in Shortcuts) + { + if (s is null || !PayloadPath.IsValidSegment(s.Name)) Fail("invalid shortcut name"); + if (!OwnsFile(s.Component, s.Target)) Fail($"shortcut {s.Name} targets a file outside its component"); + } + + foreach (var a in Associations) + { + if (a is null || !ExtensionRegex().IsMatch(a.Extension)) Fail("invalid file extension"); + if (!ProgIdRegex().IsMatch(a.ProgId) || a.ProgId.Length > 39) Fail($"invalid ProgID for {a.Extension}"); + if (string.IsNullOrWhiteSpace(a.Description) || a.Description.Length > 100) Fail($"invalid description for {a.Extension}"); + if (!OwnsFile(a.Component, a.Target)) Fail($"{a.Extension} opens a file outside its component"); + } + + bool OwnsFile(string? component, string? path) => + component is not null && path is not null && perComponent.Contains((component.ToUpperInvariant(), path.ToUpperInvariant())); + } + + /// Serializes with a fixed property order and no whitespace, so identical inputs give identical bytes. + public byte[] ToJsonBytes() => JsonSerializer.SerializeToUtf8Bytes(this, PayloadJson.Default.PayloadManifest); + + /// Parses manifest bytes; malformed JSON is reported as . + public static PayloadManifest Parse(ReadOnlySpan json) + { + try + { + return JsonSerializer.Deserialize(json, PayloadJson.Default.PayloadManifest) + ?? throw new PayloadException(PayloadError.Corrupt, "The installer manifest is empty."); + } + catch (JsonException ex) + { + throw new PayloadException(PayloadError.Corrupt, "The installer manifest is not valid JSON.", ex); + } + } + + [DoesNotReturn] + private static void Fail(string reason) => throw new PayloadException(PayloadError.Corrupt, "Invalid installer manifest: " + reason + "."); + + [GeneratedRegex("^[A-Za-z][A-Za-z0-9]{0,63}$")] + internal static partial Regex IdentifierRegex(); + + [GeneratedRegex("^[0-9a-f]{64}$")] + private static partial Regex Sha256Regex(); + + [GeneratedRegex(@"^\.[A-Za-z0-9]{1,16}$")] + private static partial Regex ExtensionRegex(); + + [GeneratedRegex(@"^[A-Za-z][A-Za-z0-9]*(\.[A-Za-z0-9]+)+$")] + private static partial Regex ProgIdRegex(); +} + +/// A selectable part of the product (Titano, Uploader, Server). +public sealed class PayloadComponent +{ + public required string Id { get; init; } + public required string DisplayName { get; init; } + public bool DefaultSelected { get; init; } + + /// Installed size in bytes (sum of the component's files). + public long EstimatedSize { get; init; } +} + +/// One installed file and where its bytes live in the data region. +public sealed class PayloadFile +{ + /// Canonical relative path (). + public required string Path { get; init; } + public required string Component { get; init; } + public long Size { get; init; } + + /// Lower-case hex SHA-256 of the uncompressed content. + public required string Sha256 { get; init; } + public PayloadCompression Compression { get; init; } + + /// Offset of the stored bytes, relative to the start of the data region. + public long Offset { get; init; } + + /// Number of stored (possibly compressed) bytes. + public long Length { get; init; } + + /// Last write time, Unix epoch seconds (UTC). + public long ModifiedUnixSeconds { get; init; } +} + +/// A shortcut to one of a component's files, created in the Start menu and/or on the desktop. +public sealed class PayloadShortcut +{ + public required string Component { get; init; } + + /// File name of the shortcut without .lnk. + public required string Name { get; init; } + + /// Payload path of the program the shortcut opens. + public required string Target { get; init; } + public bool StartMenu { get; init; } + public bool Desktop { get; init; } +} + +/// A file type registered to open with one of a component's programs ("target" "%1"). +public sealed class PayloadAssociation +{ + public required string Component { get; init; } + + /// Extension including the dot, e.g. .titano. + public required string Extension { get; init; } + public required string ProgId { get; init; } + + /// File type name shown by Explorer. + public required string Description { get; init; } + + /// Payload path of the program that opens the file. + public required string Target { get; init; } +} + +[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true, RespectNullableAnnotations = true)] +[JsonSerializable(typeof(PayloadManifest))] +internal sealed partial class PayloadJson : JsonSerializerContext; diff --git a/src/Titano.Core/Packaging/PayloadPath.cs b/src/Titano.Core/Packaging/PayloadPath.cs new file mode 100644 index 00000000..45904c7f --- /dev/null +++ b/src/Titano.Core/Packaging/PayloadPath.cs @@ -0,0 +1,68 @@ +namespace Titano.Core.Packaging; + +/// +/// Canonical payload paths: relative, forward slashes, every segment a name Windows can store. Anything rooted, +/// drive-qualified, stream-qualified (a:b), containing ./.. or empty segments is rejected, so an +/// archive can never write outside the folder it is extracted into. +/// +public static class PayloadPath +{ + public const int MaxLength = 1024; + public const int MaxSegmentLength = 255; + + private static readonly HashSet ReservedNames = new(StringComparer.OrdinalIgnoreCase) + { + "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", + "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", + "LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", + }; + + /// Path comparison used for payload paths: Windows file systems are case-insensitive. + public static StringComparer Comparer => StringComparer.OrdinalIgnoreCase; + + /// True when is a canonical, safe relative payload path. + public static bool IsValid(string? path) + { + if (string.IsNullOrEmpty(path) || path.Length > MaxLength) return false; + foreach (var segment in path.Split('/')) + { + if (!IsValidSegment(segment)) return false; + } + return true; + } + + /// True when is a single file or folder name Windows accepts verbatim. + public static bool IsValidSegment(string? name) + { + if (string.IsNullOrEmpty(name) || name.Length > MaxSegmentLength || name is "." or "..") return false; + foreach (var c in name) + { + if (c < 0x20 || c is '<' or '>' or ':' or '"' or '/' or '\\' or '|' or '?' or '*') return false; + } + // Windows silently strips trailing dots and spaces, which would alias two different names. + if (name[^1] is '.' or ' ') return false; + var dot = name.IndexOf('.', StringComparison.Ordinal); + var stem = (dot < 0 ? name : name[..dot]).TrimEnd(' '); + return !ReservedNames.Contains(stem); + } + + /// Converts a path relative to a source folder (either separator) into its canonical payload form. + public static string FromRelative(string relative) + { + var canonical = relative.Replace('\\', '/'); + if (!IsValid(canonical)) throw new PayloadException(PayloadError.UnsafePath, $"'{relative}' cannot be stored in an installer."); + return canonical; + } + + /// Full path of under ; throws when unsafe or outside the root. + public static string Resolve(string root, string relative) + { + if (!IsValid(relative)) throw new PayloadException(PayloadError.UnsafePath, $"Unsafe payload path '{relative}'."); + var fullRoot = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); + var full = Path.GetFullPath(Path.Combine(fullRoot, relative.Replace('/', Path.DirectorySeparatorChar))); + var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + if (!full.StartsWith(fullRoot + Path.DirectorySeparatorChar, comparison)) + throw new PayloadException(PayloadError.UnsafePath, $"Payload path '{relative}' leaves the target folder."); + return full; + } +} diff --git a/src/Titano.Core/Packaging/PayloadReader.cs b/src/Titano.Core/Packaging/PayloadReader.cs new file mode 100644 index 00000000..05bb94f5 --- /dev/null +++ b/src/Titano.Core/Packaging/PayloadReader.cs @@ -0,0 +1,235 @@ +using System.Buffers; +using System.IO.Compression; +using System.Security.Cryptography; + +namespace Titano.Core.Packaging; + +/// Extraction progress: bytes written so far, total bytes, and the file being written. +public readonly record struct PayloadProgress(long Done, long Total, string CurrentPath); + +/// +/// Reads a TPK1 payload from the end of an installer. Opening validates the footer, the manifest SHA-256 and every +/// manifest offset; extraction verifies each file's SHA-256 and never writes more bytes than the manifest declares. +/// +public sealed class PayloadReader : IDisposable +{ + private const int BufferSize = 1 << 16; + private readonly FileStream _stream; + private readonly long _dataOffset; + + private PayloadReader(string path, FileStream stream) + { + ArchivePath = path; + _stream = stream; + var footerOffset = LocateFooter(stream, out var footer); + var (payloadOffset, manifestLength, dataLength) = (footer.PayloadOffset, footer.ManifestLength, footer.DataLength); + if (payloadOffset < 0 || manifestLength <= 0 || manifestLength > PayloadFormat.MaxManifestLength || dataLength < 0 + || payloadOffset > footerOffset || manifestLength > footerOffset - payloadOffset + || dataLength > footerOffset - payloadOffset - manifestLength) + throw Corrupt("The installer footer points outside the file."); + if (footerOffset - payloadOffset - manifestLength - dataLength >= PayloadFormat.Alignment) + throw Corrupt("The installer has unexpected bytes before its footer."); + + var manifestBytes = new byte[manifestLength]; + stream.Position = payloadOffset; + stream.ReadExactly(manifestBytes); + if (!SHA256.HashData(manifestBytes).AsSpan().SequenceEqual(footer.ManifestHash)) + throw Corrupt("The installer manifest does not match its SHA-256."); + + Manifest = PayloadManifest.Parse(manifestBytes); + Manifest.Validate(dataLength); + PayloadOffset = payloadOffset; + _dataOffset = payloadOffset + manifestLength; + } + + /// The installer file the payload was read from. + public string ArchivePath { get; } + + /// Absolute offset where the payload starts; the bytes before it are the setup program. + public long PayloadOffset { get; } + + public PayloadManifest Manifest { get; } + + /// Opens the payload appended to the running executable. + public static PayloadReader OpenCurrentProcess() => + Open(Environment.ProcessPath ?? throw new PayloadException(PayloadError.NotFound, "The setup program path is unknown.")); + + /// Opens and validates the payload of . + public static PayloadReader Open(string path) + { + FileStream stream; + try + { + stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, BufferSize, FileOptions.RandomAccess); + } + catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException) + { + throw new PayloadException(PayloadError.NotFound, $"'{path}' does not exist.", ex); + } + try + { + return new PayloadReader(path, stream); + } + catch (IOException ex) + { + stream.Dispose(); + throw Corrupt("The installer could not be read to the end.", ex); + } + catch + { + stream.Dispose(); + throw; + } + } + + /// + /// Writes every file of under , verifying sizes and hashes. + /// The directory should be a fresh staging folder: on failure it holds partial output the caller discards. + /// + public void Extract(IReadOnlyList files, string directory, IProgress? progress = null, CancellationToken cancellationToken = default) + { + long total = 0; + foreach (var f in files) total += f.Size; + long done = 0; + var buffer = ArrayPool.Shared.Rent(BufferSize); + try + { + foreach (var file in files) + { + cancellationToken.ThrowIfCancellationRequested(); + progress?.Report(new PayloadProgress(done, total, file.Path)); + var target = PayloadPath.Resolve(directory, file.Path); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + ExtractOne(file, target, buffer, ref done, total, progress, cancellationToken); + } + progress?.Report(new PayloadProgress(done, total, string.Empty)); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + /// + /// Writes the setup program alone: the bytes before the payload, with the signature directory cleared because + /// the installer's signature covered the payload as well. Used for the uninstaller copy. + /// + public void WriteStub(string destinationPath) + { + using var output = new FileStream(destinationPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, BufferSize); + _stream.Position = 0; + CopyExactly(_stream, output, PayloadOffset); + PeImage.ClearCertificateDirectory(output); + output.Flush(flushToDisk: true); + } + + public void Dispose() => _stream.Dispose(); + + private void ExtractOne(PayloadFile file, string target, byte[] buffer, ref long done, long total, IProgress? progress, CancellationToken cancellationToken) + { + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using (var output = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, BufferSize)) + { + var window = new WindowStream(_stream, _dataOffset + file.Offset, file.Length); + using var input = file.Compression == PayloadCompression.Deflate ? new DeflateStream(window, CompressionMode.Decompress) : (Stream)window; + long written = 0; + var lastReport = 0L; + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + int read; + try + { + read = input.Read(buffer, 0, buffer.Length); + } + catch (InvalidDataException ex) + { + throw Corrupt($"'{file.Path}' is damaged in the installer.", ex); + } + if (read == 0) break; + // Never write past the declared size: a crafted entry cannot inflate beyond what the manifest promised. + if (read > file.Size - written) throw Corrupt($"'{file.Path}' is larger than the installer declares."); + output.Write(buffer, 0, read); + hash.AppendData(buffer, 0, read); + written += read; + done += read; + if (progress is not null && written - lastReport >= 4 << 20) + { + lastReport = written; + progress.Report(new PayloadProgress(done, total, file.Path)); + } + } + if (written != file.Size) throw Corrupt($"'{file.Path}' is shorter than the installer declares."); + output.Flush(flushToDisk: true); + } + if (!Convert.ToHexStringLower(hash.GetHashAndReset()).Equals(file.Sha256, StringComparison.Ordinal)) + throw Corrupt($"'{file.Path}' does not match its SHA-256."); + File.SetLastWriteTimeUtc(target, FromUnixSeconds(file.ModifiedUnixSeconds)); + } + + /// True when ends with a TPK1 footer (an installer must not become another one's stub). + internal static bool HasFooter(FileStream stream) + { + try + { + LocateFooter(stream, out _); + return true; + } + catch (PayloadException) + { + return false; + } + finally + { + stream.Position = 0; + } + } + + /// Finds the footer just before the end of the content (the file end, or the start of a signature). + private static long LocateFooter(FileStream stream, out PayloadFooter footer) + { + var end = PeImage.ContentEnd(stream); + if (end < PayloadFormat.FooterLength) throw new PayloadException(PayloadError.NotFound, "The file is too small to hold an installer payload."); + // signtool may zero-pad up to 7 bytes before the certificate table; the packer aligns, but accept either. + var tailLength = (int)Math.Min(end, PayloadFormat.FooterLength + PayloadFormat.Alignment - 1); + var tail = new byte[tailLength]; + stream.Position = end - tailLength; + stream.ReadExactly(tail); + for (var pad = 0; pad < PayloadFormat.Alignment && pad + PayloadFormat.FooterLength <= tailLength; pad++) + { + var start = tailLength - pad - PayloadFormat.FooterLength; + if (tail.AsSpan(tailLength - pad).ContainsAnyExcept((byte)0)) break; + if (PayloadFooter.TryParse(tail.AsSpan(start, PayloadFormat.FooterLength), out footer)) return end - pad - PayloadFormat.FooterLength; + } + throw new PayloadException(PayloadError.NotFound, "The file carries no installer payload."); + } + + private static void CopyExactly(Stream source, Stream destination, long count) + { + var buffer = ArrayPool.Shared.Rent(BufferSize); + try + { + while (count > 0) + { + var read = source.Read(buffer, 0, (int)Math.Min(buffer.Length, count)); + if (read == 0) throw Corrupt("The setup program is truncated."); + destination.Write(buffer, 0, read); + count -= read; + } + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + private static DateTime FromUnixSeconds(long seconds) + { + // File times start in 1601; clamp to a range every file system accepts. + const long min = 315532800; // 1980-01-01 + const long max = 253402300799; // 9999-12-31 + return DateTime.UnixEpoch.AddSeconds(Math.Clamp(seconds, min, max)); + } + + private static PayloadException Corrupt(string message, Exception? inner = null) => new(PayloadError.Corrupt, message, inner); +} diff --git a/src/Titano.Core/Packaging/PayloadWriter.cs b/src/Titano.Core/Packaging/PayloadWriter.cs new file mode 100644 index 00000000..65d7db84 --- /dev/null +++ b/src/Titano.Core/Packaging/PayloadWriter.cs @@ -0,0 +1,225 @@ +using System.Buffers; +using System.IO.Compression; +using System.Security.Cryptography; +using Titano.Core.IO; + +namespace Titano.Core.Packaging; + +/// A component to pack: its manifest identity and the folder whose whole tree it installs. +public sealed record PayloadComponentSource(string Id, string DisplayName, bool DefaultSelected, string Folder); + +/// Everything the packer needs besides the setup program. +public sealed class PayloadSource +{ + public required string Product { get; init; } + public required string Version { get; init; } + public IReadOnlyList Components { get; init; } = []; + public IReadOnlyList Shortcuts { get; init; } = []; + public IReadOnlyList Associations { get; init; } = []; +} + +/// Sizes of a written installer. +public sealed record PayloadWriteResult(long InstallerBytes, long PayloadBytes, long InstalledBytes, int FileCount); + +/// +/// Builds a self-extracting installer: the setup program followed by a TPK1 payload (). +/// Output is deterministic: files are ordered by component then ordinal path, the manifest has a fixed shape, +/// and identical content is stored once. +/// +public static class PayloadWriter +{ + private const int BufferSize = 1 << 16; + private static readonly string EmptySha256 = Convert.ToHexStringLower(SHA256.HashData([])); + + /// Packs after into (written atomically). + public static PayloadWriteResult Write(string stubPath, PayloadSource source, string outputPath, IProgress? progress = null, CancellationToken cancellationToken = default) + { + var output = Path.GetFullPath(outputPath); + var inputs = Enumerate(source, output); + long total = 0; + foreach (var input in inputs) total += new FileInfo(input.FullPath).Length; + + var spoolPath = output + "." + Guid.NewGuid().ToString("N")[..8] + ".spool"; + using var spool = new FileStream(spoolPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, BufferSize, FileOptions.DeleteOnClose); + var files = Spool(inputs, spool, total, progress, cancellationToken); + + var components = source.Components.Select(c => new PayloadComponent + { + Id = c.Id, + DisplayName = c.DisplayName, + DefaultSelected = c.DefaultSelected, + EstimatedSize = files.Where(f => f.Component == c.Id).Sum(f => f.Size), + }).ToList(); + var manifest = new PayloadManifest + { + Product = source.Product, + Version = source.Version, + Components = components, + Files = files, + Shortcuts = [.. source.Shortcuts], + Associations = [.. source.Associations], + }; + manifest.Validate(spool.Length); + var manifestBytes = manifest.ToJsonBytes(); + + var temp = AtomicFile.TempPathFor(output); + long installerLength; + try + { + using (var installer = new FileStream(temp, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, BufferSize)) + { + var payloadOffset = WriteStub(stubPath, installer); + installer.Write(manifestBytes); + spool.Position = 0; + spool.CopyTo(installer, BufferSize); + installer.Write(new byte[(PayloadFormat.Alignment - installer.Position % PayloadFormat.Alignment) % PayloadFormat.Alignment]); + Span footer = stackalloc byte[PayloadFormat.FooterLength]; + new PayloadFooter(payloadOffset, manifestBytes.Length, spool.Length, SHA256.HashData(manifestBytes)).WriteTo(footer); + installer.Write(footer); + installerLength = installer.Length; + } + AtomicFile.Commit(temp, output); + } + catch + { + if (File.Exists(temp)) File.Delete(temp); + throw; + } + + return new PayloadWriteResult(installerLength, manifestBytes.Length + spool.Length, components.Sum(c => c.EstimatedSize), files.Count); + } + + private sealed record Input(string Component, string Path, string FullPath); + + private static List Enumerate(PayloadSource source, string output) + { + var options = new EnumerationOptions { RecurseSubdirectories = true, AttributesToSkip = 0, IgnoreInaccessible = false }; + var inputs = new List(); + foreach (var component in source.Components) + { + var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(component.Folder)); + if (!Directory.Exists(root)) throw new DirectoryNotFoundException($"Component folder '{component.Folder}' does not exist."); + if (output.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException($"The installer cannot be written inside the component folder '{component.Folder}'.", nameof(output)); + inputs.AddRange(Directory.EnumerateFiles(root, "*", options) + .Select(f => new Input(component.Id, PayloadPath.FromRelative(Path.GetRelativePath(root, f)), f)) + .OrderBy(i => i.Path, StringComparer.Ordinal)); + } + return inputs; + } + + /// Compresses every input into the spool, storing each distinct content once. + private static List Spool(List inputs, FileStream spool, long total, IProgress? progress, CancellationToken cancellationToken) + { + var blobs = new Dictionary(StringComparer.Ordinal); + var files = new List(inputs.Count); + var buffer = ArrayPool.Shared.Rent(BufferSize); + long done = 0; + try + { + foreach (var input in inputs) + { + cancellationToken.ThrowIfCancellationRequested(); + progress?.Report(new PayloadProgress(done, total, input.Path)); + var start = spool.Position; + long size = 0; + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using (var file = new FileStream(input.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.SequentialScan)) + using (var deflate = new DeflateStream(spool, CompressionLevel.Optimal, leaveOpen: true)) + { + int read; + while ((read = file.Read(buffer, 0, buffer.Length)) > 0) + { + cancellationToken.ThrowIfCancellationRequested(); + hash.AppendData(buffer, 0, read); + deflate.Write(buffer, 0, read); + size += read; + } + } + done += size; + var sha = size == 0 ? EmptySha256 : Convert.ToHexStringLower(hash.GetHashAndReset()); + + (long Offset, long Length, PayloadCompression Compression) blob; + if (size == 0) + { + Rewind(spool, start); + blob = (0, 0, PayloadCompression.Stored); + } + else if (blobs.TryGetValue(sha, out var existing)) + { + Rewind(spool, start); + blob = existing; + } + else if (spool.Position - start >= size) + { + // Incompressible content (already compressed media, signed binaries): store it verbatim. + Rewind(spool, start); + using (var file = new FileStream(input.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.SequentialScan)) + CopyExactly(file, spool, size, buffer); + blob = blobs[sha] = (start, size, PayloadCompression.Stored); + } + else + { + blob = blobs[sha] = (start, spool.Position - start, PayloadCompression.Deflate); + } + + files.Add(new PayloadFile + { + Path = input.Path, + Component = input.Component, + Size = size, + Sha256 = sha, + Compression = blob.Compression, + Offset = blob.Offset, + Length = blob.Length, + ModifiedUnixSeconds = new DateTimeOffset(File.GetLastWriteTimeUtc(input.FullPath)).ToUnixTimeSeconds(), + }); + } + progress?.Report(new PayloadProgress(done, Math.Max(total, done), string.Empty)); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + return files; + } + + /// Copies the setup program, dropping an Authenticode table (the installer is signed as a whole later). + private static long WriteStub(string stubPath, FileStream installer) + { + using (var stub = new FileStream(stubPath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize)) + { + if (PayloadReader.HasFooter(stub)) throw new ArgumentException($"'{stubPath}' already carries a payload; use the plain setup program.", nameof(stubPath)); + var buffer = ArrayPool.Shared.Rent(BufferSize); + try + { + CopyExactly(stub, installer, PeImage.ContentEnd(stub), buffer); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + PeImage.ClearCertificateDirectory(installer); + installer.Seek(0, SeekOrigin.End); + return installer.Position; + } + + private static void Rewind(FileStream spool, long position) + { + spool.SetLength(position); + spool.Position = position; + } + + private static void CopyExactly(Stream source, Stream destination, long count, byte[] buffer) + { + source.Position = 0; + while (count > 0) + { + var read = source.Read(buffer, 0, (int)Math.Min(buffer.Length, count)); + if (read == 0) throw new IOException("The file changed while it was being packed."); + destination.Write(buffer, 0, read); + count -= read; + } + } +} diff --git a/src/Titano.Core/Packaging/PeImage.cs b/src/Titano.Core/Packaging/PeImage.cs new file mode 100644 index 00000000..a42f41df --- /dev/null +++ b/src/Titano.Core/Packaging/PeImage.cs @@ -0,0 +1,56 @@ +using System.Reflection.PortableExecutable; + +namespace Titano.Core.Packaging; + +/// +/// The Authenticode certificate table of a PE file. signtool appends it at the end of the file and points the +/// security data directory at it (a file offset, not an RVA). The payload footer therefore ends where the table +/// starts, and a signed stub must lose its table before a payload is appended (the installer is signed as a whole). +/// +internal readonly record struct PeImage(long CertificateOffset, long CertificateSize, long DirectoryEntryOffset) +{ + private const int SecurityDirectoryIndex = 4; + + public bool IsSigned => CertificateSize > 0; + + /// Reads the PE headers at the start of ; null when it is not a PE file. + public static PeImage? TryRead(Stream stream) + { + stream.Position = 0; + try + { + var headers = new PEHeaders(stream, (int)Math.Min(stream.Length, int.MaxValue)); + if (headers.PEHeader is not { } pe || pe.NumberOfRvaAndSizes <= SecurityDirectoryIndex) return new PeImage(0, 0, -1); + // Data directories follow the fixed optional-header fields: 96 bytes in PE32, 112 in PE32+. + var directories = headers.PEHeaderStartOffset + (pe.Magic == PEMagic.PE32Plus ? 112 : 96); + var table = pe.CertificateTableDirectory; + return new PeImage(table.RelativeVirtualAddress, table.Size, directories + SecurityDirectoryIndex * 8); + } + catch (BadImageFormatException) + { + return null; + } + finally + { + stream.Position = 0; + } + } + + /// Where meaningful content ends: the certificate table when one sits inside the file, else the file end. + public static long ContentEnd(Stream stream) + { + var image = TryRead(stream); + return image is { IsSigned: true } pe && pe.CertificateOffset > 0 && pe.CertificateOffset + pe.CertificateSize <= stream.Length + ? pe.CertificateOffset + : stream.Length; + } + + /// Clears the security directory entry so the file no longer claims a signature. + public static void ClearCertificateDirectory(Stream stream) + { + if (TryRead(stream) is not { DirectoryEntryOffset: >= 0 } pe || !pe.IsSigned) return; + stream.Position = pe.DirectoryEntryOffset; + stream.Write(stackalloc byte[8]); + stream.Position = 0; + } +} diff --git a/src/Titano.Core/Packaging/WindowStream.cs b/src/Titano.Core/Packaging/WindowStream.cs new file mode 100644 index 00000000..42a3ff45 --- /dev/null +++ b/src/Titano.Core/Packaging/WindowStream.cs @@ -0,0 +1,42 @@ +namespace Titano.Core.Packaging; + +/// Read-only view of [offset, offset + length) of a seekable stream; reads never cross the window. +internal sealed class WindowStream(Stream inner, long offset, long length) : Stream +{ + private long _position; + + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => length; + + public override long Position + { + get => _position; + set => throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span buffer) + { + var remaining = length - _position; + if (remaining <= 0 || buffer.IsEmpty) return 0; + if (buffer.Length > remaining) buffer = buffer[..(int)remaining]; + inner.Position = offset + _position; + var read = inner.Read(buffer); + if (read == 0) throw new PayloadException(PayloadError.Corrupt, "The installer ends inside a file entry."); + _position += read; + return read; + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); +} diff --git a/tests/Titano.Core.Tests/Packaging/PackagingFixture.cs b/tests/Titano.Core.Tests/Packaging/PackagingFixture.cs new file mode 100644 index 00000000..94109aee --- /dev/null +++ b/tests/Titano.Core.Tests/Packaging/PackagingFixture.cs @@ -0,0 +1,130 @@ +using System.Buffers.Binary; +using System.Security.Cryptography; +using System.Text; +using Titano.Core.Packaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Packaging; + +/// Synthetic stubs, component trees and hand-made installers for the packaging tests. +internal sealed class PackagingFixture(TestContext context) +{ + public static readonly DateTime FixedTime = new(2026, 3, 14, 15, 9, 26, DateTimeKind.Utc); + + private static readonly byte[] CraftStub = [(byte)'M', (byte)'Z', 1, 2, 3, 4, 5, 6, 7, 8, 9]; + + public string Root { get; } = context.CreateTempDirectory("packaging"); + + /// A setup "program": any bytes work, the format does not interpret the stub unless it is a PE. + public string Stub(int length = 4096) + { + var path = Path.Combine(Root, "Titano.Setup.exe"); + var bytes = new byte[length]; + new Random(7).NextBytes(bytes); + "MZ"u8.CopyTo(bytes); + File.WriteAllBytes(path, bytes); + return path; + } + + /// Creates (payload path → content) under a new folder with a fixed mtime. + public string Folder(string name, params (string Path, byte[] Content)[] files) + { + var dir = Path.Combine(Root, name); + Directory.CreateDirectory(dir); + foreach (var (relative, content) in files) + { + var path = Path.Combine(dir, relative.Replace('/', Path.DirectorySeparatorChar)); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllBytes(path, content); + File.SetLastWriteTimeUtc(path, FixedTime); + } + return dir; + } + + public static byte[] Text(string s, int repeat = 1) => Encoding.UTF8.GetBytes(string.Concat(Enumerable.Repeat(s, repeat))); + + public static byte[] Random(int length, int seed) + { + var bytes = new byte[length]; + new Random(seed).NextBytes(bytes); + return bytes; + } + + public static PayloadSource Source(params PayloadComponentSource[] components) => new() + { + Product = "Titano", + Version = "1.2.3", + Components = components, + }; + + public string Pack(string stub, PayloadSource source, string name = "Titano-Setup.exe") + { + var output = Path.Combine(Root, "out", name); + Directory.CreateDirectory(Path.GetDirectoryName(output)!); + PayloadWriter.Write(stub, source, output); + return output; + } + + /// + /// A minimal PE32+ header (no sections) followed by filler, with an optional certificate table at the end the + /// way signtool lays it out: 8-byte aligned, pointed at by the security data directory. + /// + public static byte[] PortableExecutable(int fillerLength, byte[]? certificate = null) + { + const int peOffset = 0x80; + const int optionalHeaderSize = 240; + var headerLength = peOffset + 4 + 20 + optionalHeaderSize; + var image = new byte[headerLength + fillerLength]; + "MZ"u8.CopyTo(image); + BinaryPrimitives.WriteInt32LittleEndian(image.AsSpan(0x3C), peOffset); + "PE\0\0"u8.CopyTo(image.AsSpan(peOffset)); + var coff = image.AsSpan(peOffset + 4); + BinaryPrimitives.WriteUInt16LittleEndian(coff, 0x8664); + BinaryPrimitives.WriteUInt16LittleEndian(coff[16..], optionalHeaderSize); + BinaryPrimitives.WriteUInt16LittleEndian(coff[18..], 0x0022); + var optional = image.AsSpan(peOffset + 24); + BinaryPrimitives.WriteUInt16LittleEndian(optional, 0x20B); + BinaryPrimitives.WriteUInt32LittleEndian(optional[32..], 0x1000); // SectionAlignment + BinaryPrimitives.WriteUInt32LittleEndian(optional[36..], 0x200); // FileAlignment + BinaryPrimitives.WriteUInt32LittleEndian(optional[108..], 16); // NumberOfRvaAndSizes + new Random(3).NextBytes(image.AsSpan(headerLength)); + return certificate is null ? image : Sign(image, certificate); + } + + /// Appends a certificate table and points the security directory at it, as signtool does. + public static byte[] Sign(byte[] file, byte[] certificate) + { + var aligned = (file.Length + 7) / 8 * 8; + var signed = new byte[aligned + certificate.Length]; + file.CopyTo(signed, 0); + certificate.CopyTo(signed, aligned); + var entry = SecurityDirectoryOffset(signed); + BinaryPrimitives.WriteUInt32LittleEndian(signed.AsSpan(entry), (uint)aligned); + BinaryPrimitives.WriteUInt32LittleEndian(signed.AsSpan(entry + 4), (uint)certificate.Length); + return signed; + } + + /// File offset of the security data directory entry of an image built by . + public static int SecurityDirectoryOffset(byte[] image) => + BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(0x3C)) + 4 + 20 + 112 + 4 * 8; + + /// Assembles an installer by hand from a manifest and data region, bypassing the writer's checks. + public string Craft(PayloadManifest manifest, byte[] data, string name = "crafted.exe") + { + var stub = CraftStub; + var json = manifest.ToJsonBytes(); + using var ms = new MemoryStream(); + ms.Write(stub); + ms.Write(json); + ms.Write(data); + ms.Write(new byte[(8 - ms.Length % 8) % 8]); + var footer = new byte[PayloadFormat.FooterLength]; + new PayloadFooter(stub.Length, json.Length, data.Length, SHA256.HashData(json)).WriteTo(footer); + ms.Write(footer); + var path = Path.Combine(Root, name); + File.WriteAllBytes(path, ms.ToArray()); + return path; + } + + public static string Sha256(byte[] content) => Convert.ToHexStringLower(SHA256.HashData(content)); +} diff --git a/tests/Titano.Core.Tests/Packaging/PayloadIntegrityTests.cs b/tests/Titano.Core.Tests/Packaging/PayloadIntegrityTests.cs new file mode 100644 index 00000000..a9ba9231 --- /dev/null +++ b/tests/Titano.Core.Tests/Packaging/PayloadIntegrityTests.cs @@ -0,0 +1,213 @@ +using System.Buffers.Binary; +using System.IO.Compression; +using Titano.Core.Packaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Packaging; + +public sealed class PayloadIntegrityTests(TestContext context) +{ + private readonly PackagingFixture _fx = new(context); + + private (string Installer, long PayloadOffset, byte[] Bytes) PackSample() + { + var app = _fx.Folder("app", + ("Titano.exe", PackagingFixture.Text("program ", 3000)), + ("noise.bin", PackagingFixture.Random(40_000, 5)), + ("docs/readme.txt", PackagingFixture.Text("read me ", 200))); + var installer = _fx.Pack(_fx.Stub(), PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app))); + using var reader = PayloadReader.Open(installer); + return (installer, reader.PayloadOffset, File.ReadAllBytes(installer)); + } + + [Test] + public void TamperedManifestIsRejected() + { + var (installer, offset, bytes) = PackSample(); + // Flip the first letter of "Titano" in "product":"Titano". + var at = Array.IndexOf(bytes, (byte)'T', (int)offset); + bytes[at] = (byte)'X'; + File.WriteAllBytes(installer, bytes); + var ex = Assert.Throws(() => PayloadReader.Open(installer)); + Assert.Equal(PayloadError.Corrupt, ex.Error); + Assert.Contains("SHA-256", ex.Message); + } + + [Test] + public void TamperedFooterHashIsRejected() + { + var (installer, _, bytes) = PackSample(); + bytes[^1] ^= 0x5A; + File.WriteAllBytes(installer, bytes); + Assert.Equal(PayloadError.Corrupt, Assert.Throws(() => PayloadReader.Open(installer)).Error); + } + + [Test] + public void FooterPointingOutsideTheFileIsRejected() + { + var (installer, _, bytes) = PackSample(); + BinaryPrimitives.WriteInt64LittleEndian(bytes.AsSpan(bytes.Length - PayloadFormat.FooterLength + 16), long.MaxValue - 3); + File.WriteAllBytes(installer, bytes); + Assert.Equal(PayloadError.Corrupt, Assert.Throws(() => PayloadReader.Open(installer)).Error); + } + + [Test] + public void CorruptStoredEntryFailsItsHash() + { + var (installer, _, bytes) = PackSample(); + PayloadFile noise; + long dataOffset; + using (var reader = PayloadReader.Open(installer)) + { + noise = reader.Manifest.Files.Single(f => f.Path == "noise.bin"); + dataOffset = DataOffset(bytes, reader.PayloadOffset); + } + Assert.Equal(PayloadCompression.Stored, noise.Compression); + bytes[dataOffset + noise.Offset + 1234] ^= 0xFF; + File.WriteAllBytes(installer, bytes); + + using var tampered = PayloadReader.Open(installer); + var ex = Assert.Throws(() => tampered.Extract([noise], context.CreateTempDirectory())); + Assert.Equal(PayloadError.Corrupt, ex.Error); + Assert.Contains("noise.bin", ex.Message); + } + + [Test] + public void EveryCorruptPayloadByteIsDetectedOrHarmless() + { + var (installer, offset, original) = PackSample(); + var expected = new Dictionary + { + ["Titano.exe"] = PackagingFixture.Text("program ", 3000), + ["noise.bin"] = PackagingFixture.Random(40_000, 5), + ["docs/readme.txt"] = PackagingFixture.Text("read me ", 200), + }; + var step = Math.Max(1, (int)((original.Length - offset) / 150)); + for (var at = offset; at < original.Length; at += step) + { + var bytes = (byte[])original.Clone(); + bytes[at] ^= 0xFF; + File.WriteAllBytes(installer, bytes); + var target = context.CreateTempDirectory("fuzz"); + try + { + using var reader = PayloadReader.Open(installer); + reader.Extract(reader.Manifest.Files, target); + foreach (var (path, content) in expected) + Assert.BytesEqual(content, File.ReadAllBytes(Path.Combine(target, path.Replace('/', Path.DirectorySeparatorChar))), $"flip at {at} produced wrong {path}"); + } + catch (PayloadException) + { + // Detected: the expected outcome for almost every byte. + } + } + } + + [Test] + public void TruncatedInstallersFailCleanly() + { + var (installer, _, original) = PackSample(); + var lengths = new List { 0, 1, 7, PayloadFormat.FooterLength - 1, PayloadFormat.FooterLength, original.Length - 1, original.Length - PayloadFormat.FooterLength }; + for (var n = 97; n < original.Length; n += original.Length / 60) lengths.Add(n); + foreach (var length in lengths) + { + File.WriteAllBytes(installer, original.AsSpan(0, length).ToArray()); + var ex = Assert.Throws(() => PayloadReader.Open(installer), $"truncated to {length}"); + Assert.True(ex.Error is PayloadError.NotFound or PayloadError.Corrupt, $"truncated to {length}: {ex.Error}"); + } + } + + [Test] + public void MissingFileIsReportedAsNotFound() => + Assert.Equal(PayloadError.NotFound, Assert.Throws(() => PayloadReader.Open(Path.Combine(_fx.Root, "nope.exe"))).Error); + + [Theory] + [Case("../evil.txt")] + [Case("a/../../evil.txt")] + [Case("/etc/passwd")] + [Case("C:/Windows/evil.dll")] + [Case("sub\\evil.txt")] + [Case("file.txt:stream")] + public void ManifestPathEscapingTheTargetIsRejected(string path) + { + var content = PackagingFixture.Text("x"); + var manifest = new PayloadManifest + { + Product = "Titano", + Version = "1.0.0", + Components = [new PayloadComponent { Id = "Titano", DisplayName = "Titano", DefaultSelected = true, EstimatedSize = 1 }], + Files = [new PayloadFile { Path = path, Component = "Titano", Size = 1, Sha256 = PackagingFixture.Sha256(content), Compression = PayloadCompression.Stored, Offset = 0, Length = 1 }], + }; + var installer = _fx.Craft(manifest, content); + Assert.Equal(PayloadError.UnsafePath, Assert.Throws(() => PayloadReader.Open(installer)).Error); + } + + [Test] + public void DeclaredSizeBeyondTheDeflateLimitIsRejectedUpFront() + { + var manifest = new PayloadManifest + { + Product = "Titano", + Version = "1.0.0", + Components = [new PayloadComponent { Id = "Titano", DisplayName = "Titano" }], + Files = [new PayloadFile { Path = "bomb.bin", Component = "Titano", Size = 1L << 40, Sha256 = new string('0', 64), Compression = PayloadCompression.Deflate, Offset = 0, Length = 16 }], + }; + var installer = _fx.Craft(manifest, new byte[16]); + Assert.Equal(PayloadError.Corrupt, Assert.Throws(() => PayloadReader.Open(installer)).Error); + } + + [Test] + public void EntryInflatingPastItsDeclaredSizeStopsAtTheLimit() + { + var zeros = new byte[4 << 20]; + using var compressed = new MemoryStream(); + using (var deflate = new DeflateStream(compressed, CompressionLevel.SmallestSize, leaveOpen: true)) deflate.Write(zeros); + var data = compressed.ToArray(); + var manifest = new PayloadManifest + { + Product = "Titano", + Version = "1.0.0", + Components = [new PayloadComponent { Id = "Titano", DisplayName = "Titano" }], + Files = [new PayloadFile { Path = "bomb.bin", Component = "Titano", Size = 1000, Sha256 = PackagingFixture.Sha256(new byte[1000]), Compression = PayloadCompression.Deflate, Offset = 0, Length = data.Length }], + }; + using var reader = PayloadReader.Open(_fx.Craft(manifest, data)); + var target = context.CreateTempDirectory(); + var ex = Assert.Throws(() => reader.Extract(reader.Manifest.Files, target)); + Assert.Contains("larger", ex.Message); + Assert.True(new FileInfo(Path.Combine(target, "bomb.bin")).Length <= 1000); + } + + [Test] + public void SignedStubLosesItsSignatureAndSignedInstallerStillOpens() + { + var stubBytes = PackagingFixture.PortableExecutable(5000, certificate: PackagingFixture.Random(1500, 9)); + var stub = Path.Combine(_fx.Root, "signed-stub.exe"); + File.WriteAllBytes(stub, stubBytes); + var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app", 50))); + var installer = _fx.Pack(stub, PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app))); + + var packed = File.ReadAllBytes(installer); + var entry = PackagingFixture.SecurityDirectoryOffset(packed); + Assert.Equal(0L, BinaryPrimitives.ReadInt64LittleEndian(packed.AsSpan(entry)), "stub signature directory cleared"); + + // Sign the whole installer the way signtool does, then read it back. + File.WriteAllBytes(installer, PackagingFixture.Sign(packed, PackagingFixture.Random(2048, 4))); + using var reader = PayloadReader.Open(installer); + Assert.Equal((long)(stubBytes.Length - 1500), reader.PayloadOffset); + var target = context.CreateTempDirectory(); + reader.Extract(reader.Manifest.Files, target); + Assert.BytesEqual(PackagingFixture.Text("app", 50), File.ReadAllBytes(Path.Combine(target, "Titano.exe"))); + + var copy = Path.Combine(target, "Uninstall Titano.exe"); + reader.WriteStub(copy); + var copied = File.ReadAllBytes(copy); + Assert.Equal(reader.PayloadOffset, (long)copied.Length); + Assert.Equal(0L, BinaryPrimitives.ReadInt64LittleEndian(copied.AsSpan(entry)), "uninstaller signature directory cleared"); + } + + private static long DataOffset(byte[] installer, long payloadOffset) + { + var footer = installer.AsSpan(installer.Length - PayloadFormat.FooterLength); + return payloadOffset + BinaryPrimitives.ReadInt64LittleEndian(footer[16..]); + } +} diff --git a/tests/Titano.Core.Tests/Packaging/PayloadPathTests.cs b/tests/Titano.Core.Tests/Packaging/PayloadPathTests.cs new file mode 100644 index 00000000..f6c58fd0 --- /dev/null +++ b/tests/Titano.Core.Tests/Packaging/PayloadPathTests.cs @@ -0,0 +1,60 @@ +using Titano.Core.Packaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Packaging; + +public sealed class PayloadPathTests(TestContext context) +{ + [Theory] + [Case("Titano.exe")] + [Case("lib/deep/file.dll")] + [Case("città/日本語 ✓.txt")] + [Case(".hidden")] + [Case("CONFIG.SYS")] + [Case("console.log")] + public void AcceptsCanonicalRelativePaths(string path) => Assert.True(PayloadPath.IsValid(path), path); + + [Theory] + [Case("")] + [Case("..")] + [Case("../x")] + [Case("a/../b")] + [Case("a/./b")] + [Case("a//b")] + [Case("/rooted")] + [Case("trailing/")] + [Case("C:/x")] + [Case("a\\b")] + [Case("a:stream")] + [Case("con")] + [Case("aux.txt")] + [Case("COM1")] + [Case("lpt9.log")] + [Case("dot.")] + [Case("space ")] + [Case("tab\tname")] + [Case("star*")] + public void RejectsUnsafePaths(string path) => Assert.False(PayloadPath.IsValid(path), path); + + [Test] + public void RejectsOverlongPaths() + { + Assert.False(PayloadPath.IsValid(new string('a', 256))); + Assert.False(PayloadPath.IsValid(string.Join('/', Enumerable.Repeat("abcdefghij", 100)))); + } + + [Test] + public void ResolveStaysInsideTheRoot() + { + var root = context.CreateTempDirectory(); + Assert.Equal(Path.Combine(root, "a", "b.txt"), PayloadPath.Resolve(root, "a/b.txt")); + Assert.Equal(PayloadError.UnsafePath, Assert.Throws(() => PayloadPath.Resolve(root, "../b.txt")).Error); + } + + [Test] + public void ConvertsNativeSeparators() + { + Assert.Equal("a/b/c.txt", PayloadPath.FromRelative("a\\b\\c.txt")); + Assert.Throws(() => PayloadPath.FromRelative("..\\c.txt")); + } +} diff --git a/tests/Titano.Core.Tests/Packaging/PayloadRoundTripTests.cs b/tests/Titano.Core.Tests/Packaging/PayloadRoundTripTests.cs new file mode 100644 index 00000000..55d2f575 --- /dev/null +++ b/tests/Titano.Core.Tests/Packaging/PayloadRoundTripTests.cs @@ -0,0 +1,172 @@ +using Titano.Core.Packaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Packaging; + +public sealed class PayloadRoundTripTests(TestContext context) +{ + private readonly PackagingFixture _fx = new(context); + + [Test] + public void ExtractsNestedEmptyUnicodeAndIncompressibleFilesExactly() + { + var files = new (string Path, byte[] Content)[] + { + ("Titano.exe", PackagingFixture.Text("MZ program body ", 4000)), + ("lib/deep/er/still/config.json", PackagingFixture.Text("{\"a\":1}", 50)), + ("empty.txt", []), + ("città/日本語 ✓.txt", PackagingFixture.Text("ciao 世界 ", 300)), + ("media/noise.bin", PackagingFixture.Random(3 << 20, seed: 11)), + }; + var app = _fx.Folder("app", files); + var installer = _fx.Pack(_fx.Stub(), PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app))); + + using var reader = PayloadReader.Open(installer); + var manifest = reader.Manifest; + Assert.Equal("Titano", manifest.Product); + Assert.Equal("1.2.3", manifest.Version); + Assert.Count(files.Length, manifest.Files); + Assert.Equal(files.Sum(f => (long)f.Content.Length), manifest.Components[0].EstimatedSize); + Assert.Equal(PayloadCompression.Stored, manifest.Files.Single(f => f.Path == "media/noise.bin").Compression); + Assert.Equal(PayloadCompression.Deflate, manifest.Files.Single(f => f.Path == "Titano.exe").Compression); + var empty = manifest.Files.Single(f => f.Path == "empty.txt"); + Assert.Equal(0L, empty.Length); + + var target = context.CreateTempDirectory("extract"); + reader.Extract(manifest.FilesFor(["Titano"]), target); + foreach (var (relative, content) in files) + { + var path = Path.Combine(target, relative.Replace('/', Path.DirectorySeparatorChar)); + Assert.BytesEqual(content, File.ReadAllBytes(path), relative); + Assert.Equal(PackagingFixture.FixedTime, File.GetLastWriteTimeUtc(path), relative); + } + } + + [Test] + public void ReportsProgressUpToTheTotalSize() + { + var app = _fx.Folder("app", ("a.bin", PackagingFixture.Random(9 << 20, 1)), ("b.txt", PackagingFixture.Text("b", 10))); + var installer = _fx.Pack(_fx.Stub(), PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app))); + using var reader = PayloadReader.Open(installer); + var reports = new List(); + reader.Extract(reader.Manifest.Files, context.CreateTempDirectory(), new SyncProgress(reports.Add)); + Assert.True(reports.Count >= 3); + Assert.Monotonic(reports.Select(r => (double)r.Done)); + Assert.Equal(reports[^1].Total, reports[^1].Done); + Assert.Equal((9L << 20) + 10, reports[^1].Total); + } + + [Test] + public void IdenticalInputsProduceIdenticalInstallers() + { + var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app", 999)), ("sub/z.txt", PackagingFixture.Text("z")), ("sub/a.txt", PackagingFixture.Text("a"))); + var up = _fx.Folder("uploader", ("Titano.Uploader.exe", PackagingFixture.Text("uploader", 500))); + var stub = _fx.Stub(); + var source = PackagingFixture.Source( + new PayloadComponentSource("Titano", "Titano", true, app), + new PayloadComponentSource("Uploader", "Titano Uploader", false, up)); + var first = _fx.Pack(stub, source, "first.exe"); + var second = _fx.Pack(stub, source, "second.exe"); + Assert.BytesEqual(File.ReadAllBytes(first), File.ReadAllBytes(second)); + Assert.Equal(0L, new FileInfo(first).Length % PayloadFormat.Alignment); + } + + [Test] + public void SharedFilesAreStoredOnceAndInstalledOnce() + { + var shared = PackagingFixture.Text("shared runtime ", 2000); + var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app", 100)), ("runtime.dll", shared)); + var up = _fx.Folder("uploader", ("Titano.Uploader.exe", PackagingFixture.Text("up", 100)), ("runtime.dll", shared)); + var installer = _fx.Pack(_fx.Stub(), PackagingFixture.Source( + new PayloadComponentSource("Titano", "Titano", true, app), + new PayloadComponentSource("Uploader", "Uploader", true, up))); + + using var reader = PayloadReader.Open(installer); + var copies = reader.Manifest.Files.Where(f => f.Path == "runtime.dll").ToList(); + Assert.Count(2, copies); + Assert.Equal(copies[0].Offset, copies[1].Offset); + var both = reader.Manifest.FilesFor(["Titano", "Uploader"]); + Assert.Count(3, both); + Assert.Count(2, reader.Manifest.FilesFor(["uploader"])); + Assert.Throws(() => reader.Manifest.FilesFor(["Server"])); + } + + [Test] + public void DifferentContentAtTheSamePathAcrossComponentsIsRejected() + { + var app = _fx.Folder("app", ("same.dll", PackagingFixture.Text("one"))); + var up = _fx.Folder("uploader", ("same.dll", PackagingFixture.Text("two"))); + var ex = Assert.Throws(() => _fx.Pack(_fx.Stub(), PackagingFixture.Source( + new PayloadComponentSource("Titano", "Titano", true, app), + new PayloadComponentSource("Uploader", "Uploader", true, up)))); + Assert.Equal(PayloadError.Corrupt, ex.Error); + } + + [Test] + public void ShortcutsAndAssociationsSurviveTheRoundTrip() + { + var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app"))); + var source = new PayloadSource + { + Product = "Titano", + Version = "2.0.0-beta.1", + Components = [new PayloadComponentSource("Titano", "Titano", true, app)], + Shortcuts = [new PayloadShortcut { Component = "Titano", Name = "Titano", Target = "Titano.exe", StartMenu = true, Desktop = true }], + Associations = [new PayloadAssociation { Component = "Titano", Extension = ".titano", ProgId = "Titano.Project", Description = "Titano project", Target = "Titano.exe" }], + }; + using var reader = PayloadReader.Open(_fx.Pack(_fx.Stub(), source)); + var shortcut = reader.Manifest.Shortcuts.Single(); + Assert.True(shortcut.Desktop && shortcut.StartMenu); + Assert.Equal("Titano.exe", shortcut.Target); + Assert.Equal("Titano.Project", reader.Manifest.Associations.Single().ProgId); + } + + [Test] + public void ShortcutToAFileOutsideItsComponentIsRejected() + { + var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app"))); + var source = new PayloadSource + { + Product = "Titano", + Version = "1.0.0", + Components = [new PayloadComponentSource("Titano", "Titano", true, app)], + Shortcuts = [new PayloadShortcut { Component = "Titano", Name = "Missing", Target = "Missing.exe", StartMenu = true }], + }; + Assert.Throws(() => _fx.Pack(_fx.Stub(), source)); + } + + [Test] + public void StubCopyEndsAtThePayload() + { + var stub = _fx.Stub(10_000); + var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app", 10))); + using var reader = PayloadReader.Open(_fx.Pack(stub, PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app)))); + Assert.Equal(10_000L, reader.PayloadOffset); + var copy = Path.Combine(context.CreateTempDirectory(), "Uninstall Titano.exe"); + reader.WriteStub(copy); + Assert.BytesEqual(File.ReadAllBytes(stub), File.ReadAllBytes(copy)); + Assert.Equal(PayloadError.NotFound, Assert.Throws(() => PayloadReader.Open(copy)).Error); + } + + [Test] + public void OutputInsideAComponentFolderIsRefused() + { + var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app"))); + Assert.Throws(() => PayloadWriter.Write(_fx.Stub(), PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app)), Path.Combine(app, "setup.exe"))); + } + + [Test] + public void AnInstallerCannotBeUsedAsStub() + { + var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app"))); + var source = PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app)); + var installer = _fx.Pack(_fx.Stub(), source); + Assert.Throws(() => _fx.Pack(installer, source, "nested.exe")); + } + + /// Synchronous (Progress<T> posts to the thread pool). + private sealed class SyncProgress(Action report) : IProgress + { + public void Report(T value) => report(value); + } +} From fc8df1f411021e1b67ddb17c0d4b3588fa64dc91 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:56:37 +0000 Subject: [PATCH 2/9] feat(packaging): add staged install transaction and logged file removal Extracted files land in a staging folder inside the target and are moved into place with backups of replaced files; a failed move rolls everything back. Removal deletes only logged payload paths and prunes folders left empty. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Packaging/InstallTransaction.cs | 175 ++++++++++++++++++ .../Packaging/InstallTransactionTests.cs | 103 +++++++++++ 2 files changed, 278 insertions(+) create mode 100644 src/Titano.Core/Packaging/InstallTransaction.cs create mode 100644 tests/Titano.Core.Tests/Packaging/InstallTransactionTests.cs diff --git a/src/Titano.Core/Packaging/InstallTransaction.cs b/src/Titano.Core/Packaging/InstallTransaction.cs new file mode 100644 index 00000000..fc606eaf --- /dev/null +++ b/src/Titano.Core/Packaging/InstallTransaction.cs @@ -0,0 +1,175 @@ +using Titano.Core.Diagnostics; + +namespace Titano.Core.Packaging; + +/// +/// Installs a verified file set without leaving a half-updated folder. Files are first written into a staging +/// folder inside the target (same volume, so moves are renames); then moves them into place, +/// parking every replaced file in a backup folder. If any move fails, completed moves are undone in reverse order +/// and the previous install is restored. Staging and backup folders are removed on dispose. +/// +public sealed class InstallTransaction : IDisposable +{ + private const string StagingPrefix = ".setup-staging-"; + private const string BackupPrefix = ".setup-backup-"; + private readonly string _backup; + + public InstallTransaction(string targetDirectory) + { + TargetDirectory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(targetDirectory)); + Directory.CreateDirectory(TargetDirectory); + RemoveStaleFolders(TargetDirectory); + var id = Guid.NewGuid().ToString("N")[..8]; + StagingDirectory = Path.Combine(TargetDirectory, StagingPrefix + id); + _backup = Path.Combine(TargetDirectory, BackupPrefix + id); + Directory.CreateDirectory(StagingDirectory); + } + + public string TargetDirectory { get; } + + /// Where the new files are written before . + public string StagingDirectory { get; } + + /// Moves the staged files (payload-relative paths) into the target, all or nothing. + public void Commit(IReadOnlyCollection relativePaths) + { + var completed = new List<(string Staged, string Target, string? Backup)>(relativePaths.Count); + try + { + foreach (var relative in relativePaths) + { + var staged = PayloadPath.Resolve(StagingDirectory, relative); + var target = PayloadPath.Resolve(TargetDirectory, relative); + if (!File.Exists(staged)) throw new FileNotFoundException($"Staged file '{relative}' is missing.", staged); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + string? backup = null; + if (File.Exists(target)) + { + backup = PayloadPath.Resolve(_backup, relative); + Directory.CreateDirectory(Path.GetDirectoryName(backup)!); + File.Move(target, backup); + } + try + { + File.Move(staged, target); + } + catch + { + if (backup is not null) File.Move(backup, target); + throw; + } + completed.Add((staged, target, backup)); + } + } + catch + { + Rollback(completed); + throw; + } + } + + public void Dispose() + { + TryDeleteTree(StagingDirectory); + TryDeleteTree(_backup); + } + + private static void Rollback(List<(string Staged, string Target, string? Backup)> completed) + { + for (var i = completed.Count - 1; i >= 0; i--) + { + var (staged, target, backup) = completed[i]; + try + { + File.Move(target, staged, overwrite: true); + if (backup is not null) File.Move(backup, target); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Error("setup", $"Rollback could not restore '{target}'", ex); + } + } + } + + /// Removes staging/backup folders left by an interrupted earlier run (they are always ours by name). + private static void RemoveStaleFolders(string target) + { + foreach (var dir in Directory.EnumerateDirectories(target, ".setup-*")) + { + var name = Path.GetFileName(dir); + if (name.StartsWith(StagingPrefix, StringComparison.Ordinal) || name.StartsWith(BackupPrefix, StringComparison.Ordinal)) + TryDeleteTree(dir); + } + } + + private static void TryDeleteTree(string path) + { + try + { + if (Directory.Exists(path)) Directory.Delete(path, recursive: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning("setup", $"Could not remove '{path}'", ex); + } + } +} + +/// Removes installed files by their logged payload paths, never anything else under the folder. +public static class InstalledFiles +{ + /// + /// Deletes each listed file under and prunes folders the deletion left empty (the root + /// itself only when ). Missing files count as removed; returns the paths that + /// could not be deleted, for example because a program still holds them open. + /// + public static IReadOnlyList Remove(string root, IEnumerable relativePaths, bool removeEmptyRoot = false) + { + var fullRoot = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); + var failed = new List(); + var folders = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var relative in relativePaths) + { + var path = PayloadPath.Resolve(fullRoot, relative); + try + { + if (File.Exists(path)) + { + File.SetAttributes(path, FileAttributes.Normal); + File.Delete(path); + } + folders.Add(Path.GetDirectoryName(path)!); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning("setup", $"Could not remove '{path}'", ex); + failed.Add(relative); + } + } + + // Deepest folders first, so a parent is examined after its children were pruned. + foreach (var folder in folders.OrderByDescending(f => f.Length)) + { + for (var dir = folder; dir.Length > fullRoot.Length; dir = Path.GetDirectoryName(dir)!) + { + if (!TryRemoveEmpty(dir)) break; + } + } + if (removeEmptyRoot) TryRemoveEmpty(fullRoot); + return failed; + } + + private static bool TryRemoveEmpty(string dir) + { + try + { + if (!Directory.Exists(dir) || Directory.EnumerateFileSystemEntries(dir).Any()) return false; + Directory.Delete(dir); + return true; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return false; + } + } +} diff --git a/tests/Titano.Core.Tests/Packaging/InstallTransactionTests.cs b/tests/Titano.Core.Tests/Packaging/InstallTransactionTests.cs new file mode 100644 index 00000000..c79e980b --- /dev/null +++ b/tests/Titano.Core.Tests/Packaging/InstallTransactionTests.cs @@ -0,0 +1,103 @@ +using Titano.Core.Packaging; +using Titano.Testing; + +namespace Titano.Core.Tests.Packaging; + +public sealed class InstallTransactionTests(TestContext context) +{ + [Test] + public void CommitReplacesFilesAndCleansUp() + { + var target = context.CreateTempDirectory(); + File.WriteAllText(Path.Combine(target, "Titano.exe"), "old"); + File.WriteAllText(Path.Combine(target, "user-notes.txt"), "keep"); + + using (var tx = new InstallTransaction(target)) + { + Write(tx.StagingDirectory, "Titano.exe", "new"); + Write(tx.StagingDirectory, "lib/new.dll", "dll"); + tx.Commit(["Titano.exe", "lib/new.dll"]); + } + + Assert.Equal("new", File.ReadAllText(Path.Combine(target, "Titano.exe"))); + Assert.Equal("dll", File.ReadAllText(Path.Combine(target, "lib", "new.dll"))); + Assert.Equal("keep", File.ReadAllText(Path.Combine(target, "user-notes.txt"))); + Assert.Empty(Directory.GetDirectories(target, ".setup-*")); + } + + [Test] + public void FailedCommitRestoresThePreviousInstall() + { + var target = context.CreateTempDirectory(); + File.WriteAllText(Path.Combine(target, "Titano.exe"), "old"); + // A folder where the new version has a file makes the second move fail. + Directory.CreateDirectory(Path.Combine(target, "blocked")); + File.WriteAllText(Path.Combine(target, "blocked", "inside.txt"), "x"); + + using (var tx = new InstallTransaction(target)) + { + Write(tx.StagingDirectory, "Titano.exe", "new"); + Write(tx.StagingDirectory, "added.dll", "added"); + Write(tx.StagingDirectory, "blocked", "file"); + // Linux reports IOException, Windows UnauthorizedAccessException for a file moved onto a folder. + var ex = Assert.Throws(() => tx.Commit(["Titano.exe", "added.dll", "blocked"])); + Assert.True(ex is IOException or UnauthorizedAccessException, ex.GetType().Name); + } + + Assert.Equal("old", File.ReadAllText(Path.Combine(target, "Titano.exe"))); + Assert.FileMissing(Path.Combine(target, "added.dll")); + Assert.Equal("x", File.ReadAllText(Path.Combine(target, "blocked", "inside.txt"))); + Assert.Empty(Directory.GetDirectories(target, ".setup-*")); + } + + [Test] + public void StaleStagingFoldersFromAnInterruptedRunAreRemoved() + { + var target = context.CreateTempDirectory(); + Directory.CreateDirectory(Path.Combine(target, ".setup-staging-deadbeef", "sub")); + Directory.CreateDirectory(Path.Combine(target, ".setup-other")); + using (new InstallTransaction(target)) + { + } + Assert.False(Directory.Exists(Path.Combine(target, ".setup-staging-deadbeef"))); + Assert.True(Directory.Exists(Path.Combine(target, ".setup-other"))); + } + + [Test] + public void RemoveDeletesOnlyLoggedFilesAndPrunesEmptyFolders() + { + var root = context.CreateTempDirectory(); + Write(root, "Titano.exe", "a"); + Write(root, "lib/x/y.dll", "b"); + Write(root, "lib/keep.txt", "user"); + + var failed = InstalledFiles.Remove(root, ["Titano.exe", "lib/x/y.dll", "already-gone.dll"], removeEmptyRoot: true); + + Assert.Empty(failed); + Assert.FileMissing(Path.Combine(root, "Titano.exe")); + Assert.False(Directory.Exists(Path.Combine(root, "lib", "x"))); + Assert.Equal("user", File.ReadAllText(Path.Combine(root, "lib", "keep.txt"))); + Assert.True(Directory.Exists(root), "root keeps unlisted files"); + + InstalledFiles.Remove(root, ["lib/keep.txt"], removeEmptyRoot: true); + Assert.False(Directory.Exists(root)); + } + + [Test] + public void RemoveRefusesPathsOutsideTheRoot() + { + var parent = context.CreateTempDirectory(); + var root = Path.Combine(parent, "install"); + Directory.CreateDirectory(root); + Write(parent, "outside.txt", "precious"); + Assert.Throws(() => InstalledFiles.Remove(root, ["../outside.txt"])); + Assert.FileExists(Path.Combine(parent, "outside.txt")); + } + + private static void Write(string root, string relative, string content) + { + var path = Path.Combine(root, relative.Replace('/', Path.DirectorySeparatorChar)); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, content); + } +} From c591aced94dbdfc1eaebbb5bab1f80e2fb555ade Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:58:29 +0000 Subject: [PATCH 3/9] feat(tools): add pack-installer command Appends a TPK1 payload to Titano.Setup.exe from repeatable --component Id=folder options, as release.yml invokes it. Known components (Titano, Uploader, Server) get display names, default selection, Start menu/desktop shortcuts and the .titano file type; prints file count and sizes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Packaging/PayloadWriter.cs | 4 +- .../Commands/PackInstallerCommand.cs | 109 ++++++++++++++++++ src/Titano.Tools/Program.cs | 1 + 3 files changed, 112 insertions(+), 2 deletions(-) create mode 100644 src/Titano.Tools/Commands/PackInstallerCommand.cs diff --git a/src/Titano.Core/Packaging/PayloadWriter.cs b/src/Titano.Core/Packaging/PayloadWriter.cs index 65d7db84..09b3d5ac 100644 --- a/src/Titano.Core/Packaging/PayloadWriter.cs +++ b/src/Titano.Core/Packaging/PayloadWriter.cs @@ -100,7 +100,7 @@ public static class PayloadWriter var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(component.Folder)); if (!Directory.Exists(root)) throw new DirectoryNotFoundException($"Component folder '{component.Folder}' does not exist."); if (output.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException($"The installer cannot be written inside the component folder '{component.Folder}'.", nameof(output)); + throw new ArgumentException($"The installer cannot be written inside the component folder '{component.Folder}'."); inputs.AddRange(Directory.EnumerateFiles(root, "*", options) .Select(f => new Input(component.Id, PayloadPath.FromRelative(Path.GetRelativePath(root, f)), f)) .OrderBy(i => i.Path, StringComparer.Ordinal)); @@ -189,7 +189,7 @@ public static class PayloadWriter { using (var stub = new FileStream(stubPath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize)) { - if (PayloadReader.HasFooter(stub)) throw new ArgumentException($"'{stubPath}' already carries a payload; use the plain setup program.", nameof(stubPath)); + if (PayloadReader.HasFooter(stub)) throw new ArgumentException($"'{stubPath}' already carries a payload; use the plain setup program."); var buffer = ArrayPool.Shared.Rent(BufferSize); try { diff --git a/src/Titano.Tools/Commands/PackInstallerCommand.cs b/src/Titano.Tools/Commands/PackInstallerCommand.cs new file mode 100644 index 00000000..24720315 --- /dev/null +++ b/src/Titano.Tools/Commands/PackInstallerCommand.cs @@ -0,0 +1,109 @@ +using System.Globalization; +using Titano.Core.Packaging; + +namespace Titano.Tools.Commands; + +/// +/// pack-installer --setup Titano.Setup.exe --product Titano --version 1.2.3 --component Id=folder … --out file: +/// appends a TPK1 payload (BRIEF §18) to the setup program. Known component ids carry their display name, default +/// selection, shortcuts and file types; unknown ids are packed as plain, preselected components. +/// +internal sealed class PackInstallerCommand : ICommand +{ + private sealed record KnownComponent(string DisplayName, bool DefaultSelected, string Program, bool Desktop, PayloadAssociation? Association); + + private static readonly Dictionary Known = new(StringComparer.OrdinalIgnoreCase) + { + ["Titano"] = new("Titano", true, "Titano.exe", Desktop: true, + new PayloadAssociation { Component = "Titano", Extension = ".titano", ProgId = "Titano.Project", Description = "Titano project", Target = "Titano.exe" }), + ["Uploader"] = new("Titano Uploader", true, "Titano.Uploader.exe", Desktop: true, null), + ["Server"] = new("Titano Server", false, "Titano.Server.exe", Desktop: false, null), + }; + + public string Name => "pack-installer"; + public string Summary => "--setup --product --version --component Id=dir … --out "; + + public Task RunAsync(string[] args) + { + var options = Parse(args); + var setup = Required(options, "setup"); + var output = Required(options, "out"); + if (!File.Exists(setup)) throw new ToolException($"Setup program '{setup}' not found."); + if (!options.TryGetValue("component", out var specs)) throw new ToolException("At least one --component Id=folder is required."); + + var components = new List(); + var shortcuts = new List(); + var associations = new List(); + foreach (var spec in specs) + { + var eq = spec.IndexOf('=', StringComparison.Ordinal); + if (eq <= 0 || eq == spec.Length - 1) throw new ToolException($"--component expects Id=folder, got '{spec}'."); + var id = spec[..eq]; + var folder = spec[(eq + 1)..]; + if (!PayloadManifest.IdentifierRegex().IsMatch(id)) throw new ToolException($"Component id '{id}' must be letters and digits."); + if (components.Any(c => c.Id.Equals(id, StringComparison.OrdinalIgnoreCase))) throw new ToolException($"Component '{id}' given twice."); + if (!Directory.Exists(folder)) throw new ToolException($"Component folder '{folder}' not found."); + + if (!Known.TryGetValue(id, out var known)) + { + components.Add(new PayloadComponentSource(id, id, true, folder)); + continue; + } + components.Add(new PayloadComponentSource(id, known.DisplayName, known.DefaultSelected, folder)); + if (!File.Exists(Path.Combine(folder, known.Program))) + { + Console.Error.WriteLine($"warning: {id} has no {known.Program}; no shortcut or file type registered."); + continue; + } + shortcuts.Add(new PayloadShortcut { Component = id, Name = known.DisplayName, Target = known.Program, StartMenu = true, Desktop = known.Desktop }); + if (known.Association is { } association) associations.Add(association); + } + + var source = new PayloadSource + { + Product = Required(options, "product"), + Version = Required(options, "version"), + Components = components, + Shortcuts = shortcuts, + Associations = associations, + }; + try + { + Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(output))!); + var result = PayloadWriter.Write(setup, source, output); + Console.WriteLine(string.Create(CultureInfo.InvariantCulture, + $"{output}: {result.FileCount} files in {components.Count} component(s), {Megabytes(result.InstallerBytes)} ({result.InstallerBytes:N0} bytes), installs {Megabytes(result.InstalledBytes)}")); + return Task.FromResult(0); + } + catch (Exception ex) when (ex is PayloadException or ArgumentException or IOException) + { + throw new ToolException("pack-installer: " + ex.Message); + } + } + + /// --key value pairs; every key may repeat (only --component is meant to). + private static Dictionary> Parse(string[] args) + { + var allowed = new HashSet(StringComparer.OrdinalIgnoreCase) { "setup", "product", "version", "component", "out" }; + var options = new Dictionary>(StringComparer.OrdinalIgnoreCase); + for (var i = 0; i < args.Length; i++) + { + if (!args[i].StartsWith("--", StringComparison.Ordinal) || !allowed.Contains(args[i][2..])) + throw new ToolException($"Unexpected argument '{args[i]}'."); + if (i + 1 >= args.Length) throw new ToolException($"{args[i]} needs a value."); + var key = args[i][2..]; + if (!options.TryGetValue(key, out var values)) options[key] = values = []; + values.Add(args[++i]); + } + return options; + } + + private static string Required(Dictionary> options, string key) + { + if (!options.TryGetValue(key, out var values) || string.IsNullOrWhiteSpace(values[^1])) throw new ToolException($"--{key} is required."); + if (values.Count > 1) throw new ToolException($"--{key} given more than once."); + return values[0]; + } + + private static string Megabytes(long bytes) => (bytes / 1_000_000d).ToString("0.0", CultureInfo.InvariantCulture) + " MB"; +} diff --git a/src/Titano.Tools/Program.cs b/src/Titano.Tools/Program.cs index d5575d16..78f6e44d 100644 --- a/src/Titano.Tools/Program.cs +++ b/src/Titano.Tools/Program.cs @@ -8,6 +8,7 @@ var commands = new ICommand[] new XamlLintCommand(), new PackageGuardCommand(), new ChangelogCommand(), + new PackInstallerCommand(), }; if (args.Length == 0 || args[0] is "-h" or "--help" or "help") From 5b5f38c91d41a1984ec36a4a09c6fb3f763d3011 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:15:59 +0000 Subject: [PATCH 4/9] feat(i18n): add Setup strings and tooltips English and Italian labels, messages and Tooltips.Setup.* entries for the installer window; error sentences carry the long-text budget. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/en/Setup.resx | 49 ++++++++++++++++++++++++++++++++++++++++ i18n/en/Tooltips.resx | 24 ++++++++++++++++++++ i18n/it/Setup.it.resx | 49 ++++++++++++++++++++++++++++++++++++++++ i18n/it/Tooltips.it.resx | 24 ++++++++++++++++++++ 4 files changed, 146 insertions(+) create mode 100644 i18n/en/Setup.resx create mode 100644 i18n/it/Setup.it.resx diff --git a/i18n/en/Setup.resx b/i18n/en/Setup.resx new file mode 100644 index 00000000..23dab393 --- /dev/null +++ b/i18n/en/Setup.resx @@ -0,0 +1,49 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Cancel + Close + Close programs + Install + Launch + Retry + Uninstall + Update + Server for Windows + Titano + Uploader + {0} is installed. + {0} was removed. + Windows denied access to the folder.long + The command line is not valid.long + There is not enough free disk space.long + Administrator approval was declined.long + Setup could not finish.long + {0} is not installed.long + This installer is damaged; download it again.long + {0} did not close.long + Some files could not be removed.long + Components + Folder + Language + Options + Install for + Browse + Version {0} · installed {1} + Version {0} + Desktop shortcut + Start when done + Start menu + Installing {0} + Removing {0} + Close {0} to continue. + All users + Just me + {0} needed + Remove my data + {0} Setup + Remove {0} + diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index b6393fa1..1d5c8702 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -27,6 +27,30 @@ Dark interface (default) Light interface Follow the Windows app mode + Install in Program Files for every account · asks for administrator approval + Return to the options without changing anything + Choose the installation folder + Close setup + Ask the running programs to close · each one handles its unsaved work + Install this program + Runs Titano Server on this PC for other devices and render nodes + The desktop app to import, archive and render time-lapses + Sends photos from watched folders to a Titano Server + Add shortcuts to the desktop + Where the programs are installed · your data stays in its own folder + Enter a full folder path that is not a drive root or a system folder + Copy the selected programs and register them with Windows + Folder of the installed programs + Install in your user folder · no administrator rights needed + Language of this setup + Open the program when setup finishes + Open the installed program + Already installed here · uninstall it first to change folder or scope + Also delete database, settings and logs in %LOCALAPPDATA%\Titano · photos in archives are not touched + Run the same step again + Add the programs to the Start menu + Remove programs, shortcuts and file types · your data is kept unless selected + Replace the installed version in place · your data is kept Collapse navigation to icons Show navigation names Stop the current job · it can be resumed later diff --git a/i18n/it/Setup.it.resx b/i18n/it/Setup.it.resx new file mode 100644 index 00000000..b2588356 --- /dev/null +++ b/i18n/it/Setup.it.resx @@ -0,0 +1,49 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Annulla + Chiudi + Chiudi programmi + Installa + Avvia + Riprova + Disinstalla + Aggiorna + Server per Windows + Titano + Uploader + {0} è installato. + {0} è stato rimosso. + Windows ha negato l'accesso alla cartella.long + La riga di comando non è valida.long + Lo spazio libero su disco non è sufficiente.long + L'autorizzazione di amministratore è stata negata.long + L'installazione non è stata completata.long + {0} non è installato.long + Il programma di installazione è danneggiato; scaricalo di nuovo.long + {0} non si è chiuso.long + Alcuni file non sono stati rimossi.long + Componenti + Cartella + Lingua + Opzioni + Installa per + Sfoglia + Versione {0} · installata {1} + Versione {0} + Collegamento sul desktop + Avvia al termine + Menu Start + Installazione di {0} + Rimozione di {0} + Chiudi {0} per continuare. + Tutti gli utenti + Solo per me + {0} necessari + Rimuovi i miei dati + Installazione di {0} + Rimozione di {0} + diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index 6892a5f4..ca09ebc5 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -27,6 +27,30 @@ Interfaccia scura (predefinita) Interfaccia chiara Segui la modalità app di Windows + Installa in Programmi per tutti gli account · chiede l'autorizzazione di amministratore + Torna alle opzioni senza modificare nulla + Scegli la cartella di installazione + Chiudi l'installazione + Chiedi ai programmi aperti di chiudersi · ognuno gestisce il lavoro non salvato + Installa questo programma + Esegue Titano Server su questo PC per altri dispositivi e nodi di rendering + L'app desktop per importare, archiviare e renderizzare time-lapse + Invia le foto dalle cartelle monitorate a un Titano Server + Aggiungi collegamenti al desktop + Dove vengono installati i programmi · i tuoi dati restano nella loro cartella + Inserisci il percorso completo di una cartella che non sia la radice di un'unità o una cartella di sistema + Copia i programmi selezionati e registrali in Windows + Cartella dei programmi installati + Installa nella tua cartella utente · non servono diritti di amministratore + Lingua di questa installazione + Apri il programma al termine dell'installazione + Apri il programma installato + Già installato qui · disinstallalo prima per cambiare cartella o ambito + Elimina anche database, impostazioni e log in %LOCALAPPDATA%\Titano · le foto negli archivi non vengono toccate + Esegui di nuovo lo stesso passaggio + Aggiungi i programmi al menu Start + Rimuovi programmi, collegamenti e tipi di file · i dati restano salvo diversa scelta + Sostituisci la versione installata · i tuoi dati restano Riduci la navigazione alle icone Mostra i nomi della navigazione Ferma l'attività in corso · potrai riprenderla From c97b4fb82c622f06ef8c51c0c0007bd079173354 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 10:16:20 +0000 Subject: [PATCH 5/9] feat(setup): add one-screen installer, uninstaller and silent mode Titano.Setup reads the TPK1 payload from its own executable and installs per user (%LOCALAPPDATA%\Programs) or for all users (Program Files, relaunched elevated through ShellExecuteEx "runas"). Extraction is hash-verified into a staging folder and committed with rollback; upgrades replace files in place, remove obsolete ones and never touch %LOCALAPPDATA%\Titano. - Components, scope, folder (IFileOpenDialog picker), desktop and Start menu shortcuts (IShellLinkW), start-after-install, language picker - Add/Remove Programs entry, .titano file type, install log - /uninstall [/S] removes only logged files, shortcuts and registry entries; user data only when "Remove my data" is ticked; the uninstaller deletes itself through a temporary helper copy - Silent switches /S /DIR= /COMPONENTS= /ALLUSERS /NODESKTOP /NOSTARTMENU /LAUNCH /LANG= with documented exit codes; running programs are asked to close, never killed Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Setup/App.cs | 76 +++ src/Titano.Setup/App.xaml | 4 - src/Titano.Setup/App.xaml.cs | 7 - src/Titano.Setup/Cli/SetupArguments.cs | 105 +++++ src/Titano.Setup/Cli/SetupExitCode.cs | 41 ++ src/Titano.Setup/Engine/Elevation.cs | 79 ++++ src/Titano.Setup/Engine/InstallEngine.cs | 149 ++++++ src/Titano.Setup/Engine/InstallLog.cs | 60 +++ src/Titano.Setup/Engine/InstallPlan.cs | 37 ++ src/Titano.Setup/Engine/RunningPrograms.cs | 54 +++ src/Titano.Setup/Engine/SelfCleanup.cs | 83 ++++ src/Titano.Setup/Engine/SetupPaths.cs | 78 ++++ src/Titano.Setup/Engine/SetupRegistry.cs | 110 +++++ src/Titano.Setup/Engine/SilentSetup.cs | 99 ++++ src/Titano.Setup/Engine/UninstallEngine.cs | 106 +++++ src/Titano.Setup/Interop/FolderPicker.cs | 129 ++++++ src/Titano.Setup/Interop/NativeMethods.cs | 57 +++ src/Titano.Setup/Interop/ShellLink.cs | 61 +++ src/Titano.Setup/Interop/StaThread.cs | 33 ++ src/Titano.Setup/Program.cs | 60 +++ src/Titano.Setup/Titano.Setup.csproj | 6 + src/Titano.Setup/Views/ComponentOption.cs | 49 ++ src/Titano.Setup/Views/SetupViewModel.cs | 514 +++++++++++++++++++++ src/Titano.Setup/Views/SetupWindow.xaml | 152 ++++++ src/Titano.Setup/Views/SetupWindow.xaml.cs | 45 ++ 25 files changed, 2183 insertions(+), 11 deletions(-) create mode 100644 src/Titano.Setup/App.cs delete mode 100644 src/Titano.Setup/App.xaml delete mode 100644 src/Titano.Setup/App.xaml.cs create mode 100644 src/Titano.Setup/Cli/SetupArguments.cs create mode 100644 src/Titano.Setup/Cli/SetupExitCode.cs create mode 100644 src/Titano.Setup/Engine/Elevation.cs create mode 100644 src/Titano.Setup/Engine/InstallEngine.cs create mode 100644 src/Titano.Setup/Engine/InstallLog.cs create mode 100644 src/Titano.Setup/Engine/InstallPlan.cs create mode 100644 src/Titano.Setup/Engine/RunningPrograms.cs create mode 100644 src/Titano.Setup/Engine/SelfCleanup.cs create mode 100644 src/Titano.Setup/Engine/SetupPaths.cs create mode 100644 src/Titano.Setup/Engine/SetupRegistry.cs create mode 100644 src/Titano.Setup/Engine/SilentSetup.cs create mode 100644 src/Titano.Setup/Engine/UninstallEngine.cs create mode 100644 src/Titano.Setup/Interop/FolderPicker.cs create mode 100644 src/Titano.Setup/Interop/NativeMethods.cs create mode 100644 src/Titano.Setup/Interop/ShellLink.cs create mode 100644 src/Titano.Setup/Interop/StaThread.cs create mode 100644 src/Titano.Setup/Program.cs create mode 100644 src/Titano.Setup/Views/ComponentOption.cs create mode 100644 src/Titano.Setup/Views/SetupViewModel.cs create mode 100644 src/Titano.Setup/Views/SetupWindow.xaml create mode 100644 src/Titano.Setup/Views/SetupWindow.xaml.cs diff --git a/src/Titano.Setup/App.cs b/src/Titano.Setup/App.cs new file mode 100644 index 00000000..b6868594 --- /dev/null +++ b/src/Titano.Setup/App.cs @@ -0,0 +1,76 @@ +using System.Windows; +using Titano.Core.Diagnostics; +using Titano.Core.Packaging; +using Titano.Setup.Cli; +using Titano.Setup.Engine; +using Titano.Setup.Views; +using Titano.Ui.Theming; + +namespace Titano.Setup; + +/// +/// Interactive setup: opens the payload (or, for /uninstall, the installation), elevates an all-users +/// uninstall up front, and shows the setup window. The exit code is the view model's outcome. +/// +internal sealed class App(SetupArguments arguments) : Application +{ + protected override void OnStartup(StartupEventArgs e) + { + base.OnStartup(e); + ShutdownMode = ShutdownMode.OnExplicitShutdown; + ThemeManager.Initialize(this, AppTheme.Dark); + _ = StartAsync(); + } + + private async Task StartAsync() + { + try + { + var model = arguments.Uninstall ? await ForUninstallAsync() : ForInstall(); + if (model is null) return; + var window = new SetupWindow(model); + MainWindow = window; + window.Closed += (_, _) => + { + model.Dispose(); + Shutdown((int)model.ExitCode); + }; + window.Show(); + } + catch (Exception ex) + { + Log.Error("setup", "Setup could not start", ex); + Shutdown((int)SetupExitCode.Failed); + } + } + + private SetupViewModel ForInstall() + { + PayloadReader? payload = null; + try + { + payload = PayloadReader.OpenCurrentProcess(); + return SetupViewModel.ForInstall(arguments, payload); + } + catch (Exception ex) when (ex is PayloadException or SetupException) + { + payload?.Dispose(); + Log.Error("setup", "Cannot install", ex); + return SetupViewModel.ForFailure(arguments, SilentSetup.CodeFor(ex)); + } + } + + /// The uninstall window, or null when this process handed over to an elevated copy and is shutting down. + private async Task ForUninstallAsync() + { + var product = UninstallEngine.Locate(arguments.Directory, SilentSetup.PayloadProduct()); + if (product is null) return SetupViewModel.ForFailure(arguments, SetupExitCode.NotInstalled); + if (product.Log.Scope == InstallScope.AllUsers && !Elevation.IsElevated) + { + var code = arguments.Elevated ? SetupExitCode.ElevationDeclined : await Elevation.RunElevatedAsync(arguments, null); + Shutdown((int)code); + return null; + } + return SetupViewModel.ForUninstall(arguments, product); + } +} diff --git a/src/Titano.Setup/App.xaml b/src/Titano.Setup/App.xaml deleted file mode 100644 index f0e5e815..00000000 --- a/src/Titano.Setup/App.xaml +++ /dev/null @@ -1,4 +0,0 @@ - - diff --git a/src/Titano.Setup/App.xaml.cs b/src/Titano.Setup/App.xaml.cs deleted file mode 100644 index 24976df3..00000000 --- a/src/Titano.Setup/App.xaml.cs +++ /dev/null @@ -1,7 +0,0 @@ -using System.Windows; - -namespace Titano.Setup; - -public partial class App : Application -{ -} diff --git a/src/Titano.Setup/Cli/SetupArguments.cs b/src/Titano.Setup/Cli/SetupArguments.cs new file mode 100644 index 00000000..e5f54e19 --- /dev/null +++ b/src/Titano.Setup/Cli/SetupArguments.cs @@ -0,0 +1,105 @@ +using System.Text; + +namespace Titano.Setup.Cli; + +/// +/// Command-line switches, case-insensitive, with / or -: +/// /S silent · /DIR=path · /COMPONENTS=Titano,Uploader · /ALLUSERS · /NODESKTOP · +/// /NOSTARTMENU · /LAUNCH · /LANG=it · /uninstall. +/// Internal: /ELEVATED (relaunched for administrator rights), /CLEANUP=path /WAITPID=n (removes the +/// uninstaller after the uninstall process exits). +/// +internal sealed record SetupArguments +{ + public bool Silent { get; init; } + public bool Uninstall { get; init; } + public string? Directory { get; init; } + public IReadOnlyList? Components { get; init; } + public bool AllUsers { get; init; } + public bool NoDesktopShortcut { get; init; } + public bool NoStartMenu { get; init; } + public bool Launch { get; init; } + public string? Language { get; init; } + public bool Elevated { get; init; } + public string? CleanupTarget { get; init; } + public int WaitProcessId { get; init; } + + /// Parses ; throws for unknown or malformed switches. + public static SetupArguments Parse(IEnumerable args) + { + var result = new SetupArguments(); + foreach (var arg in args) + { + if (arg.Length < 2 || arg[0] is not ('/' or '-')) throw new ArgumentException($"Unexpected argument '{arg}'."); + var eq = arg.IndexOf('=', StringComparison.Ordinal); + var name = (eq < 0 ? arg[1..] : arg[1..eq]).ToUpperInvariant(); + var value = eq < 0 ? null : arg[(eq + 1)..]; + result = (name, value) switch + { + ("S", null) => result with { Silent = true }, + ("UNINSTALL", null) => result with { Uninstall = true }, + ("ALLUSERS", null) => result with { AllUsers = true }, + ("NODESKTOP", null) => result with { NoDesktopShortcut = true }, + ("NOSTARTMENU", null) => result with { NoStartMenu = true }, + ("LAUNCH", null) => result with { Launch = true }, + ("ELEVATED", null) => result with { Elevated = true }, + ("DIR", { Length: > 0 }) => result with { Directory = value.Trim('"') }, + ("LANG", { Length: > 0 }) => result with { Language = value }, + ("COMPONENTS", { Length: > 0 }) => result with { Components = value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) }, + ("CLEANUP", { Length: > 0 }) => result with { CleanupTarget = value.Trim('"') }, + ("WAITPID", { Length: > 0 }) when int.TryParse(value, out var pid) && pid > 0 => result with { WaitProcessId = pid }, + _ => throw new ArgumentException($"Unknown or malformed switch '{arg}'."), + }; + } + if (result.CleanupTarget is not null && result.WaitProcessId == 0) throw new ArgumentException("/CLEANUP needs /WAITPID."); + return result; + } + + /// The switches that reproduce these arguments, for relaunching with administrator rights. + public IEnumerable ToSwitches() + { + if (Uninstall) yield return "/uninstall"; + if (Silent) yield return "/S"; + if (Directory is not null) yield return "/DIR=" + Directory; + if (Components is not null) yield return "/COMPONENTS=" + string.Join(',', Components); + if (AllUsers) yield return "/ALLUSERS"; + if (NoDesktopShortcut) yield return "/NODESKTOP"; + if (NoStartMenu) yield return "/NOSTARTMENU"; + if (Launch) yield return "/LAUNCH"; + if (Language is not null) yield return "/LANG=" + Language; + if (Elevated) yield return "/ELEVATED"; + } + + /// + /// Joins arguments into one command line that CommandLineToArgvW splits back into the same strings + /// (quotes around spaces, backslashes doubled before a quote). + /// + public static string JoinCommandLine(IEnumerable arguments) + { + var sb = new StringBuilder(); + foreach (var argument in arguments) + { + if (sb.Length > 0) sb.Append(' '); + if (argument.Length > 0 && argument.IndexOfAny([' ', '\t', '"']) < 0) + { + sb.Append(argument); + continue; + } + sb.Append('"'); + var backslashes = 0; + foreach (var c in argument) + { + if (c == '\\') + { + backslashes++; + continue; + } + sb.Append('\\', c == '"' ? backslashes * 2 + 1 : backslashes); + backslashes = 0; + sb.Append(c); + } + sb.Append('\\', backslashes * 2).Append('"'); + } + return sb.ToString(); + } +} diff --git a/src/Titano.Setup/Cli/SetupExitCode.cs b/src/Titano.Setup/Cli/SetupExitCode.cs new file mode 100644 index 00000000..d044bd45 --- /dev/null +++ b/src/Titano.Setup/Cli/SetupExitCode.cs @@ -0,0 +1,41 @@ +namespace Titano.Setup.Cli; + +/// Process exit codes of Titano.Setup (stable contract for silent deployments). +internal enum SetupExitCode +{ + Success = 0, + + /// Installation or removal did not complete; the setup log in %TEMP%\Titano Setup has details. + Failed = 1, + + InvalidArguments = 2, + + /// The installer carries no payload or the payload is damaged. + PayloadInvalid = 3, + + /// All-users operation and the administrator prompt was declined. + ElevationDeclined = 4, + + /// An installed program did not close when asked to. + ProgramRunning = 5, + + /// /uninstall found no installation. + NotInstalled = 6, + + DiskFull = 7, + + /// The window was closed before anything changed. + Cancelled = 8, + + /// + /// Internal: an instance relaunched with administrator rights finished and asks its unelevated parent to start + /// the program, so the program does not run elevated. The parent turns it into . + /// + LaunchRequested = 100, +} + +/// A setup failure that maps to a specific exit code and message. +internal sealed class SetupException(SetupExitCode code, string message) : Exception(message) +{ + public SetupExitCode Code { get; } = code; +} diff --git a/src/Titano.Setup/Engine/Elevation.cs b/src/Titano.Setup/Engine/Elevation.cs new file mode 100644 index 00000000..91f7936a --- /dev/null +++ b/src/Titano.Setup/Engine/Elevation.cs @@ -0,0 +1,79 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.Security.Principal; +using Titano.Setup.Cli; +using Titano.Setup.Interop; + +namespace Titano.Setup.Engine; + +/// +/// Administrator rights for all-users operations. Setup runs asInvoker and, only when needed, starts itself +/// again through ShellExecuteEx with the runas verb (the UAC prompt) and the same switches plus /ELEVATED. +/// +internal static class Elevation +{ + public static bool IsElevated + { + get + { + using var identity = WindowsIdentity.GetCurrent(); + return new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator); + } + } + + /// + /// Runs this program elevated with and waits for it; see . + /// Returns when the prompt was refused. + /// + public static async Task RunElevatedAsync(SetupArguments arguments, string? launchProgram) => + Start(arguments, IntPtr.Zero) is { } child ? await WaitAsync(child, launchProgram).ConfigureAwait(false) : SetupExitCode.ElevationDeclined; + + /// Starts this program elevated (UAC prompt owned by ); null when the user declines. + public static Process? Start(SetupArguments arguments, IntPtr owner) + { + var start = new ProcessStartInfo(Environment.ProcessPath ?? throw new InvalidOperationException("Unknown setup path.")) + { + UseShellExecute = true, + Verb = "runas", + Arguments = SetupArguments.JoinCommandLine((arguments with { Elevated = true }).ToSwitches()), + ErrorDialogParentHandle = owner, + }; + try + { + return Process.Start(start) ?? throw new InvalidOperationException("The elevated setup did not start."); + } + catch (Win32Exception ex) when (ex.NativeErrorCode == NativeMethods.ERROR_CANCELLED) + { + return null; + } + } + + /// + /// Waits for the elevated copy and returns its exit code; when it asks for it, starts + /// from this unelevated process so the program does not run as administrator. + /// + public static async Task WaitAsync(Process child, string? launchProgram) + { + using (child) + { + await child.WaitForExitAsync().ConfigureAwait(false); + var code = (SetupExitCode)child.ExitCode; + if (code != SetupExitCode.LaunchRequested) return code; + if (launchProgram is not null) Launcher.Start(launchProgram); + return SetupExitCode.Success; + } + } +} + +/// Starts an installed program the way Explorer does. +internal static class Launcher +{ + public static void Start(string program) + { + using var process = Process.Start(new ProcessStartInfo(program) + { + UseShellExecute = true, + WorkingDirectory = System.IO.Path.GetDirectoryName(program)!, + }); + } +} diff --git a/src/Titano.Setup/Engine/InstallEngine.cs b/src/Titano.Setup/Engine/InstallEngine.cs new file mode 100644 index 00000000..dc216279 --- /dev/null +++ b/src/Titano.Setup/Engine/InstallEngine.cs @@ -0,0 +1,149 @@ +using System.IO; +using System.Reflection; +using Titano.Core.Diagnostics; +using Titano.Core.Packaging; +using Titano.Setup.Cli; +using Titano.Setup.Interop; + +namespace Titano.Setup.Engine; + +/// What to install, where and with which shortcuts. +internal sealed record InstallRequest(string Directory, InstallScope Scope, IReadOnlyList Components, bool DesktopShortcuts, bool StartMenuShortcuts); + +/// Overall progress (0–1) and the file being written. +internal readonly record struct SetupProgress(double Fraction, string CurrentFile); + +/// +/// Installs or upgrades in place from the payload: verified extraction into staging, an all-or-nothing move into +/// the folder, removal of files the previous version shipped and this one does not, then shortcuts, file types and +/// the Add/Remove Programs entry. The user data folder is never touched. +/// +internal sealed class InstallEngine(PayloadReader payload) +{ + private const double ExtractShare = 0.9; + + public PayloadManifest Manifest => payload.Manifest; + + /// Bytes the selected components occupy once installed, uninstaller included. + public long RequiredBytes(IEnumerable components) => Manifest.FilesFor(components).Sum(f => f.Size) + payload.PayloadOffset; + + /// Payload path of the program to start after installing: the first shortcut target among the components. + public string? LaunchTarget(IEnumerable components) + { + var selected = new HashSet(components, StringComparer.OrdinalIgnoreCase); + return Manifest.Shortcuts.FirstOrDefault(s => selected.Contains(s.Component))?.Target; + } + + public InstallLog Install(InstallRequest request, IProgress? progress, CancellationToken cancellationToken) + { + var directory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(request.Directory)); + var product = Manifest.Product; + var uninstaller = SetupPaths.UninstallerName(product); + var files = Manifest.FilesFor(request.Components); + if (files.Any(f => PayloadPath.Comparer.Equals(f.Path, uninstaller) || PayloadPath.Comparer.Equals(f.Path, InstallLog.FileName))) + throw new PayloadException(PayloadError.Corrupt, "The payload overwrites setup's own files."); + EnsureFreeSpace(directory, RequiredBytes(request.Components)); + var previous = InstallLog.TryLoad(directory); + Log.Info("setup", $"Installing {product} {Manifest.Version} ({string.Join(",", request.Components)}) to '{directory}' for {request.Scope}"); + + using (var transaction = new InstallTransaction(directory)) + { + var extractProgress = progress is null ? null : new MappedProgress(progress, 0, ExtractShare); + payload.Extract(files, transaction.StagingDirectory, extractProgress, cancellationToken); + payload.WriteStub(Path.Combine(transaction.StagingDirectory, uninstaller)); + cancellationToken.ThrowIfCancellationRequested(); + transaction.Commit([.. files.Select(f => f.Path), uninstaller]); + } + progress?.Report(new SetupProgress(ExtractShare, string.Empty)); + + var shortcuts = PlanShortcuts(request, directory); + var fileTypes = PlanFileTypes(request); + var log = new InstallLog + { + Product = product, + Version = Manifest.Version, + Scope = request.Scope, + Components = [.. request.Components], + Files = [.. files.Select(f => f.Path)], + Shortcuts = [.. shortcuts.Select(s => s.Link)], + Associations = [.. fileTypes.Select(a => new InstalledAssociation(a.Extension, a.ProgId))], + }; + if (previous is not null) RemoveLeftovers(directory, previous, log); + // Saved before registration so that an uninstall can always undo whatever follows. + log.Save(directory); + + foreach (var (link, target, name) in shortcuts) ShellLink.Create(link, target, name); + foreach (var a in fileTypes) + SetupRegistry.RegisterFileType(request.Scope, a.Extension, a.ProgId, a.Description, PayloadPath.Resolve(directory, a.Target)); + if (fileTypes.Count > 0 || previous?.Associations.Count > 0) NativeMethods.NotifyAssociationsChanged(); + + var uninstallerPath = Path.Combine(directory, uninstaller); + var icon = LaunchTarget(request.Components) is { } main ? PayloadPath.Resolve(directory, main) : uninstallerPath; + SetupRegistry.WriteUninstallEntry(request.Scope, SetupPaths.ProductKey(product), new UninstallEntry( + product, Manifest.Version, Publisher, directory, uninstallerPath, icon, RequiredBytes(request.Components), AboutUrl)); + progress?.Report(new SetupProgress(1, string.Empty)); + Log.Info("setup", $"Installed {files.Count} files"); + return log; + } + + private static string Publisher => typeof(InstallEngine).Assembly.GetCustomAttribute()?.Company ?? "Titano"; + + private static string? AboutUrl => + typeof(InstallEngine).Assembly.GetCustomAttributes().FirstOrDefault(a => a.Key == "TitanoReleasesRepo")?.Value is { Length: > 0 } repo + ? "https://github.com/" + repo + : null; + + private List<(string Link, string Target, string Name)> PlanShortcuts(InstallRequest request, string directory) + { + var selected = new HashSet(request.Components, StringComparer.OrdinalIgnoreCase); + var result = new List<(string, string, string)>(); + foreach (var s in Manifest.Shortcuts.Where(s => selected.Contains(s.Component))) + { + var target = PayloadPath.Resolve(directory, s.Target); + if (s.StartMenu && request.StartMenuShortcuts) result.Add((Path.Combine(SetupPaths.StartMenu(request.Scope), s.Name + ".lnk"), target, s.Name)); + if (s.Desktop && request.DesktopShortcuts) result.Add((Path.Combine(SetupPaths.Desktop(request.Scope), s.Name + ".lnk"), target, s.Name)); + } + return result; + } + + private List PlanFileTypes(InstallRequest request) + { + var selected = new HashSet(request.Components, StringComparer.OrdinalIgnoreCase); + return Manifest.Associations.Where(a => selected.Contains(a.Component)).ToList(); + } + + /// Removes what the previous version installed and this one no longer does (files, shortcuts, file types). + private static void RemoveLeftovers(string directory, InstallLog previous, InstallLog current) + { + var obsolete = previous.Files.Where(PayloadPath.IsValid).Except(current.Files, PayloadPath.Comparer).ToList(); + if (obsolete.Count > 0) InstalledFiles.Remove(directory, obsolete); + foreach (var link in previous.Shortcuts.Except(current.Shortcuts, StringComparer.OrdinalIgnoreCase)) + UninstallEngine.DeleteShortcut(link, previous.Scope); + foreach (var a in previous.Associations.Except(current.Associations)) + { + if (SetupRegistry.IsValidFileType(a.Extension, a.ProgId)) SetupRegistry.UnregisterFileType(previous.Scope, a.Extension, a.ProgId); + } + } + + private static void EnsureFreeSpace(string directory, long required) + { + long available; + try + { + available = new DriveInfo(Path.GetPathRoot(directory)!).AvailableFreeSpace; + } + catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException) + { + // Network shares have no DriveInfo; the copy itself reports a full disk. + return; + } + if (available < required) throw new SetupException(SetupExitCode.DiskFull, $"{required:N0} bytes needed, {available:N0} available."); + } + + /// Maps extraction progress onto a slice of the overall bar. + private sealed class MappedProgress(IProgress target, double from, double to) : IProgress + { + public void Report(PayloadProgress value) => + target.Report(new SetupProgress(from + (to - from) * (value.Total == 0 ? 1 : (double)value.Done / value.Total), value.CurrentPath)); + } +} diff --git a/src/Titano.Setup/Engine/InstallLog.cs b/src/Titano.Setup/Engine/InstallLog.cs new file mode 100644 index 00000000..4cdc6f5c --- /dev/null +++ b/src/Titano.Setup/Engine/InstallLog.cs @@ -0,0 +1,60 @@ +using System.IO; +using System.Text.Json; +using System.Text.Json.Serialization; +using Titano.Core.IO; + +namespace Titano.Setup.Engine; + +/// +/// Record of one installation, kept as install-log.json in the install folder. The uninstaller carries no +/// payload, so everything it removes comes from here: payload files, shortcuts and file types. User data is never +/// listed. +/// +internal sealed class InstallLog +{ + public const string FileName = "install-log.json"; + + public int FormatVersion { get; set; } = 1; + public required string Product { get; set; } + public required string Version { get; set; } + public InstallScope Scope { get; set; } + public List Components { get; set; } = []; + + /// Installed payload paths, relative to the install folder (the uninstaller and this log excluded). + public List Files { get; set; } = []; + + /// Full paths of the shortcuts setup created. + public List Shortcuts { get; set; } = []; + public List Associations { get; set; } = []; + + [JsonIgnore] + public string ProductKey => SetupPaths.ProductKey(Product); + + [JsonIgnore] + public string UninstallerName => SetupPaths.UninstallerName(Product); + + /// The log in , or null when there is none or it is unreadable. + public static InstallLog? TryLoad(string directory) + { + var path = Path.Combine(directory, FileName); + try + { + return File.Exists(path) ? JsonSerializer.Deserialize(File.ReadAllBytes(path), InstallLogJson.Default.InstallLog) : null; + } + catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException) + { + Titano.Core.Diagnostics.Log.Warning("setup", $"Install log '{path}' is unreadable", ex); + return null; + } + } + + public void Save(string directory) => + AtomicFile.WriteAllBytes(Path.Combine(directory, FileName), JsonSerializer.SerializeToUtf8Bytes(this, InstallLogJson.Default.InstallLog)); +} + +/// A file type registered by setup. +internal sealed record InstalledAssociation(string Extension, string ProgId); + +[JsonSourceGenerationOptions(WriteIndented = true, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true, RespectNullableAnnotations = true)] +[JsonSerializable(typeof(InstallLog))] +internal sealed partial class InstallLogJson : JsonSerializerContext; diff --git a/src/Titano.Setup/Engine/InstallPlan.cs b/src/Titano.Setup/Engine/InstallPlan.cs new file mode 100644 index 00000000..6b9f3cdc --- /dev/null +++ b/src/Titano.Setup/Engine/InstallPlan.cs @@ -0,0 +1,37 @@ +using Titano.Core.Packaging; +using Titano.Setup.Cli; + +namespace Titano.Setup.Engine; + +/// +/// Where and what to install before the user changes anything: an existing installation fixes folder and scope +/// (upgrade in place) and suggests its components; otherwise the switches, then the manifest defaults, apply. +/// +internal sealed record InstallPlan(InstallScope Scope, string Directory, IReadOnlyList Components, ExistingInstall? Existing) +{ + public static InstallPlan Resolve(PayloadManifest manifest, SetupArguments arguments) + { + var existing = SetupRegistry.FindInstall(SetupPaths.ProductKey(manifest.Product)); + var scope = existing?.Scope ?? (arguments.AllUsers ? InstallScope.AllUsers : InstallScope.CurrentUser); + var directory = existing?.Directory ?? arguments.Directory ?? SetupPaths.DefaultDirectory(scope, manifest.Product); + + IReadOnlyList components; + if (arguments.Components is { } requested) + { + var unknown = requested.FirstOrDefault(id => manifest.FindComponent(id) is null); + if (unknown is not null) throw new SetupException(SetupExitCode.InvalidArguments, $"Unknown component '{unknown}'."); + components = [.. requested.Select(id => manifest.FindComponent(id)!.Id).Distinct()]; + } + else + { + var previous = existing is null ? null : InstallLog.TryLoad(existing.Directory)?.Components; + var kept = previous?.Select(manifest.FindComponent).OfType().Select(c => c.Id).ToList(); + components = kept is { Count: > 0 } ? kept : [.. manifest.Components.Where(c => c.DefaultSelected).Select(c => c.Id)]; + } + return new InstallPlan(scope, directory, components, existing); + } + + /// Executables to look for among running processes: the new payload's and the previous install's. + public static IEnumerable Programs(PayloadManifest manifest, string directory) => + manifest.Files.Select(f => f.Path).Concat(InstallLog.TryLoad(directory)?.Files ?? []); +} diff --git a/src/Titano.Setup/Engine/RunningPrograms.cs b/src/Titano.Setup/Engine/RunningPrograms.cs new file mode 100644 index 00000000..b060a50b --- /dev/null +++ b/src/Titano.Setup/Engine/RunningPrograms.cs @@ -0,0 +1,54 @@ +using System.Diagnostics; +using System.IO; +using Titano.Setup.Interop; + +namespace Titano.Setup.Engine; + +/// +/// Installed programs that are running. Setup only ever asks them to close (WM_CLOSE to the main window, as when +/// the user clicks ✕); it never terminates a process. +/// +internal static class RunningPrograms +{ + /// Processes of (payload paths) started from inside . + public static IReadOnlyList Find(string directory, IEnumerable executables) + { + var names = executables + .Where(p => p.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) && !p.Contains('/', StringComparison.Ordinal)) + .Select(Path.GetFileNameWithoutExtension) + .Distinct(StringComparer.OrdinalIgnoreCase); + var found = new List(); + foreach (var name in names) + { + foreach (var process in Process.GetProcessesByName(name)) + { + var image = process.Id == Environment.ProcessId ? null : NativeMethods.ProcessImagePath(process.Id); + if (image is not null && SetupPaths.IsSameOrInside(image, directory)) found.Add(process); + else process.Dispose(); + } + } + return found; + } + + /// Display names ("Titano", "Titano.Uploader") of the given processes, for the prompt. + public static string Describe(IReadOnlyList processes) => + string.Join(", ", processes.Select(p => p.ProcessName).Distinct(StringComparer.OrdinalIgnoreCase)); + + /// Asks each process to close and waits up to ; returns those still running. + public static async Task> CloseAsync(IReadOnlyList processes, TimeSpan timeout) + { + foreach (var process in processes) + { + if (!process.HasExited) process.CloseMainWindow(); + } + using var cts = new CancellationTokenSource(timeout); + try + { + await Task.WhenAll(processes.Select(p => p.WaitForExitAsync(cts.Token))).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + } + return processes.Where(p => !p.HasExited).ToList(); + } +} diff --git a/src/Titano.Setup/Engine/SelfCleanup.cs b/src/Titano.Setup/Engine/SelfCleanup.cs new file mode 100644 index 00000000..3f296f16 --- /dev/null +++ b/src/Titano.Setup/Engine/SelfCleanup.cs @@ -0,0 +1,83 @@ +using System.Diagnostics; +using System.IO; +using System.Threading; +using Titano.Core.Diagnostics; +using Titano.Setup.Cli; +using Titano.Setup.Interop; + +namespace Titano.Setup.Engine; + +/// +/// Removes the uninstaller, which cannot delete its own running executable. It copies itself to a fresh folder in +/// %TEMP% and starts the copy with /CLEANUP=<uninstaller> /WAITPID=<its id>; the copy waits for the +/// uninstaller to exit, deletes it and the then-empty install folder, and exits. The copy itself is scheduled for +/// deletion at the next restart when setup has administrator rights; otherwise Windows' temporary-file cleanup +/// removes it. This works for per-user installs, where MoveFileEx(MOVEFILE_DELAY_UNTIL_REBOOT) is not allowed. +/// +internal static class SelfCleanup +{ + private const string Prefix = "Uninstall "; + + /// Starts the helper that deletes once this process has exited. + public static void Schedule(string uninstallerPath) + { + var folder = Path.Combine(Path.GetTempPath(), "Titano Setup", "cleanup-" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(folder); + var copy = Path.Combine(folder, "Titano-Cleanup.exe"); + File.Copy(Environment.ProcessPath!, copy); + var start = new ProcessStartInfo(copy) { UseShellExecute = false, CreateNoWindow = true }; + start.ArgumentList.Add("/CLEANUP=" + uninstallerPath); + start.ArgumentList.Add("/WAITPID=" + Environment.ProcessId.ToString(System.Globalization.CultureInfo.InvariantCulture)); + using var helper = Process.Start(start); + Log.Info("setup", $"Cleanup helper started for '{uninstallerPath}'"); + } + + /// The helper side: waits for , then removes the uninstaller and its empty folder. + public static SetupExitCode Run(string uninstallerPath, int processId) + { + var name = Path.GetFileName(uninstallerPath); + if (!Path.IsPathFullyQualified(uninstallerPath) || !name.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase) + || !name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) + return SetupExitCode.InvalidArguments; + + try + { + using var parent = Process.GetProcessById(processId); + parent.WaitForExit(TimeSpan.FromMinutes(2)); + } + catch (ArgumentException) + { + // Already exited. + } + + var removed = false; + for (var attempt = 0; attempt < 20 && !removed; attempt++) + { + try + { + if (File.Exists(uninstallerPath)) File.Delete(uninstallerPath); + removed = true; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Thread.Sleep(500); + } + } + var folder = Path.GetDirectoryName(uninstallerPath)!; + try + { + if (Directory.Exists(folder) && !Directory.EnumerateFileSystemEntries(folder).Any()) Directory.Delete(folder); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning("setup", $"Install folder '{folder}' not removed", ex); + } + + if (Elevation.IsElevated && Environment.ProcessPath is { } self) + { + NativeMethods.DeleteAtReboot(self); + NativeMethods.DeleteAtReboot(Path.GetDirectoryName(self)!); + } + return removed ? SetupExitCode.Success : SetupExitCode.Failed; + } +} diff --git a/src/Titano.Setup/Engine/SetupPaths.cs b/src/Titano.Setup/Engine/SetupPaths.cs new file mode 100644 index 00000000..4a1ac77d --- /dev/null +++ b/src/Titano.Setup/Engine/SetupPaths.cs @@ -0,0 +1,78 @@ +using System.IO; +using Titano.Core.Packaging; + +namespace Titano.Setup.Engine; + +/// Per-user (no administrator rights) or machine-wide installation. +internal enum InstallScope +{ + CurrentUser, + AllUsers, +} + +/// Folders and names that depend on the product and the install scope. +internal static class SetupPaths +{ + private static string LocalAppData => Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + + /// %LOCALAPPDATA%\Programs\<product> for the current user, Program Files\<product> for all users. + public static string DefaultDirectory(InstallScope scope, string product) => Path.Combine( + scope == InstallScope.AllUsers ? Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) : Path.Combine(LocalAppData, "Programs"), + product); + + public static string StartMenu(InstallScope scope) => + Environment.GetFolderPath(scope == InstallScope.AllUsers ? Environment.SpecialFolder.CommonPrograms : Environment.SpecialFolder.Programs); + + public static string Desktop(InstallScope scope) => + Environment.GetFolderPath(scope == InstallScope.AllUsers ? Environment.SpecialFolder.CommonDesktopDirectory : Environment.SpecialFolder.DesktopDirectory); + + /// + /// %LOCALAPPDATA%\Titano: database, settings, logs and caches of the desktop programs. Installing and + /// upgrading never touch it; uninstall removes it only when the user asks. + /// + public static string UserData => Path.Combine(LocalAppData, "Titano"); + + /// Setup's own log files (%TEMP%\Titano Setup), outside the user data folder. + public static string LogDirectory => Path.Combine(Path.GetTempPath(), "Titano Setup"); + + /// Registry key name under …\CurrentVersion\Uninstall: the product name without spaces or symbols. + public static string ProductKey(string product) => string.Concat(product.Where(char.IsAsciiLetterOrDigit)); + + public static string UninstallerName(string product) => $"Uninstall {product}.exe"; + + /// + /// True for an absolute local or UNC folder whose names Windows stores verbatim, that is not a drive root, not + /// inside the Windows folder and not the user data folder. + /// + public static bool IsUsableInstallDirectory(string? path) + { + if (string.IsNullOrWhiteSpace(path) || !Path.IsPathFullyQualified(path) || path.IndexOfAny(Path.GetInvalidPathChars()) >= 0) return false; + string full; + try + { + full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)); + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) + { + return false; + } + var root = Path.TrimEndingDirectorySeparator(Path.GetPathRoot(full) ?? string.Empty); + if (full.Length <= root.Length) return false; + foreach (var segment in full[root.Length..].Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)) + { + if (!PayloadPath.IsValidSegment(segment)) return false; + } + return !IsSameOrInside(full, Environment.GetFolderPath(Environment.SpecialFolder.Windows)) + && !IsSameOrInside(full, UserData) + && !IsSameOrInside(UserData, full); + } + + /// True when is or lies inside it (case-insensitive). + public static bool IsSameOrInside(string path, string folder) + { + if (folder.Length == 0) return false; + var a = Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)); + var b = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder)); + return a.Equals(b, StringComparison.OrdinalIgnoreCase) || a.StartsWith(b + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/src/Titano.Setup/Engine/SetupRegistry.cs b/src/Titano.Setup/Engine/SetupRegistry.cs new file mode 100644 index 00000000..006c7703 --- /dev/null +++ b/src/Titano.Setup/Engine/SetupRegistry.cs @@ -0,0 +1,110 @@ +using System.Globalization; +using System.IO; +using System.Text.RegularExpressions; +using Microsoft.Win32; + +namespace Titano.Setup.Engine; + +/// An installation found in Add/Remove Programs. +internal sealed record ExistingInstall(InstallScope Scope, string Directory, string Version); + +/// Values written to the Add/Remove Programs entry. +internal sealed record UninstallEntry(string DisplayName, string Version, string Publisher, string Directory, string UninstallerPath, string DisplayIcon, long EstimatedBytes, string? AboutUrl); + +/// +/// Registry state owned by setup: the Add/Remove Programs entry under +/// Software\Microsoft\Windows\CurrentVersion\Uninstall\<key> and file types under Software\Classes, +/// in HKCU for per-user installs and HKLM for all-users installs. +/// +internal static partial class SetupRegistry +{ + private const string UninstallRoot = @"Software\Microsoft\Windows\CurrentVersion\Uninstall\"; + private const string ClassesRoot = @"Software\Classes\"; + + private static RegistryKey Hive(InstallScope scope) => scope == InstallScope.AllUsers ? Registry.LocalMachine : Registry.CurrentUser; + + /// The installation registered under whose folder still exists, current user first. + public static ExistingInstall? FindInstall(string productKey) + { + foreach (var scope in (ReadOnlySpan)[InstallScope.CurrentUser, InstallScope.AllUsers]) + { + using var key = Hive(scope).OpenSubKey(UninstallRoot + productKey); + if (key?.GetValue("InstallLocation") is string directory && Directory.Exists(directory)) + return new ExistingInstall(scope, directory, key.GetValue("DisplayVersion") as string ?? string.Empty); + } + return null; + } + + public static void WriteUninstallEntry(InstallScope scope, string productKey, UninstallEntry entry) + { + using var key = Hive(scope).CreateSubKey(UninstallRoot + productKey, writable: true); + var quoted = "\"" + entry.UninstallerPath + "\""; + key.SetValue("DisplayName", entry.DisplayName); + key.SetValue("DisplayVersion", entry.Version); + key.SetValue("Publisher", entry.Publisher); + key.SetValue("DisplayIcon", entry.DisplayIcon + ",0"); + key.SetValue("InstallLocation", entry.Directory); + key.SetValue("InstallDate", DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture)); + key.SetValue("UninstallString", quoted + " /uninstall"); + key.SetValue("QuietUninstallString", quoted + " /uninstall /S"); + key.SetValue("EstimatedSize", (int)Math.Min(int.MaxValue, (entry.EstimatedBytes + 1023) / 1024), RegistryValueKind.DWord); + key.SetValue("NoModify", 1, RegistryValueKind.DWord); + key.SetValue("NoRepair", 1, RegistryValueKind.DWord); + if (entry.AboutUrl is not null) key.SetValue("URLInfoAbout", entry.AboutUrl); + } + + public static void DeleteUninstallEntry(InstallScope scope, string productKey) => + Hive(scope).DeleteSubKeyTree(UninstallRoot + productKey, throwOnMissingSubKey: false); + + /// Registers to open with "program" "%1" under . + public static void RegisterFileType(InstallScope scope, string extension, string progId, string description, string program) + { + EnsureValid(extension, progId); + var hive = Hive(scope); + using (var type = hive.CreateSubKey(ClassesRoot + progId, writable: true)) + { + type.SetValue(string.Empty, description); + using (var icon = type.CreateSubKey("DefaultIcon", writable: true)) icon.SetValue(string.Empty, "\"" + program + "\",0"); + using var command = type.CreateSubKey(@"shell\open\command", writable: true); + command.SetValue(string.Empty, "\"" + program + "\" \"%1\""); + } + using var ext = hive.CreateSubKey(ClassesRoot + extension, writable: true); + ext.SetValue(string.Empty, progId); + using var openWith = ext.CreateSubKey("OpenWithProgids", writable: true); + openWith.SetValue(progId, string.Empty); + } + + /// Removes the ProgID and detaches the extension, leaving other programs' registrations intact. + public static void UnregisterFileType(InstallScope scope, string extension, string progId) + { + EnsureValid(extension, progId); + var hive = Hive(scope); + hive.DeleteSubKeyTree(ClassesRoot + progId, throwOnMissingSubKey: false); + using (var ext = hive.OpenSubKey(ClassesRoot + extension, writable: true)) + { + if (ext is null) return; + if (ext.GetValue(string.Empty) is string current && current.Equals(progId, StringComparison.OrdinalIgnoreCase)) ext.DeleteValue(string.Empty, false); + using (var openWith = ext.OpenSubKey("OpenWithProgids", writable: true)) + { + openWith?.DeleteValue(progId, false); + if (openWith is { ValueCount: 0, SubKeyCount: 0 }) ext.DeleteSubKey("OpenWithProgids", false); + } + if (ext.ValueCount > 0 || ext.SubKeyCount > 0) return; + } + hive.DeleteSubKey(ClassesRoot + extension, throwOnMissingSubKey: false); + } + + /// Guards registry paths built from a log file: an extension and a dotted ProgID, nothing else. + public static bool IsValidFileType(string extension, string progId) => ExtensionRegex().IsMatch(extension) && ProgIdRegex().IsMatch(progId); + + private static void EnsureValid(string extension, string progId) + { + if (!IsValidFileType(extension, progId)) throw new ArgumentException($"Invalid file type '{extension}' / '{progId}'."); + } + + [GeneratedRegex(@"^\.[A-Za-z0-9]{1,16}$")] + private static partial Regex ExtensionRegex(); + + [GeneratedRegex(@"^[A-Za-z][A-Za-z0-9]*(\.[A-Za-z0-9]+)+$")] + private static partial Regex ProgIdRegex(); +} diff --git a/src/Titano.Setup/Engine/SilentSetup.cs b/src/Titano.Setup/Engine/SilentSetup.cs new file mode 100644 index 00000000..a0c7a398 --- /dev/null +++ b/src/Titano.Setup/Engine/SilentSetup.cs @@ -0,0 +1,99 @@ +using System.IO; +using Titano.Core.Diagnostics; +using Titano.Core.Packaging; +using Titano.Setup.Cli; + +namespace Titano.Setup.Engine; + +/// +/// /S: install or uninstall without a window, reporting only through the exit code and the setup log. +/// Running programs are asked to close; if they do not, setup stops with . +/// Silent uninstall never removes user data. +/// +internal static class SilentSetup +{ + public static readonly TimeSpan CloseTimeout = TimeSpan.FromSeconds(20); + + public static async Task RunAsync(SetupArguments arguments) + { + try + { + return arguments.Uninstall ? await UninstallAsync(arguments).ConfigureAwait(false) : await InstallAsync(arguments).ConfigureAwait(false); + } + catch (Exception ex) + { + Log.Error("setup", "Silent setup failed", ex); + return CodeFor(ex); + } + } + + /// Exit code for a failure. + public static SetupExitCode CodeFor(Exception ex) => ex switch + { + SetupException s => s.Code, + PayloadException => SetupExitCode.PayloadInvalid, + // ERROR_DISK_FULL / ERROR_HANDLE_DISK_FULL + IOException { HResult: unchecked((int)0x80070070) or unchecked((int)0x80070027) } => SetupExitCode.DiskFull, + _ => SetupExitCode.Failed, + }; + + private static async Task InstallAsync(SetupArguments arguments) + { + using var payload = PayloadReader.OpenCurrentProcess(); + var engine = new InstallEngine(payload); + var plan = InstallPlan.Resolve(engine.Manifest, arguments); + if (plan.Existing is not null && arguments.Directory is not null && !SetupPaths.IsSameOrInside(arguments.Directory, plan.Directory)) + Log.Warning("setup", $"/DIR ignored: {engine.Manifest.Product} is already installed in '{plan.Directory}'"); + if (!SetupPaths.IsUsableInstallDirectory(plan.Directory)) return SetupExitCode.InvalidArguments; + if (plan.Components.Count == 0) return SetupExitCode.InvalidArguments; + + var launch = arguments.Launch && engine.LaunchTarget(plan.Components) is { } target ? PayloadPath.Resolve(plan.Directory, target) : null; + if (plan.Scope == InstallScope.AllUsers && !Elevation.IsElevated) + return arguments.Elevated ? SetupExitCode.ElevationDeclined : await Elevation.RunElevatedAsync(arguments, launch).ConfigureAwait(false); + + if (!await CloseProgramsAsync(plan.Directory, InstallPlan.Programs(engine.Manifest, plan.Directory)).ConfigureAwait(false)) + return SetupExitCode.ProgramRunning; + var request = new InstallRequest(plan.Directory, plan.Scope, plan.Components, !arguments.NoDesktopShortcut, !arguments.NoStartMenu); + engine.Install(request, null, CancellationToken.None); + + if (launch is null) return SetupExitCode.Success; + if (arguments.Elevated) return SetupExitCode.LaunchRequested; + Launcher.Start(launch); + return SetupExitCode.Success; + } + + private static async Task UninstallAsync(SetupArguments arguments) + { + var product = UninstallEngine.Locate(arguments.Directory, PayloadProduct()); + if (product is null) return SetupExitCode.NotInstalled; + if (product.Log.Scope == InstallScope.AllUsers && !Elevation.IsElevated) + return arguments.Elevated ? SetupExitCode.ElevationDeclined : await Elevation.RunElevatedAsync(arguments, null).ConfigureAwait(false); + if (!await CloseProgramsAsync(product.Directory, product.Log.Files).ConfigureAwait(false)) return SetupExitCode.ProgramRunning; + UninstallEngine.Uninstall(product, removeUserData: false, null); + return SetupExitCode.Success; + } + + /// The product named by this program's payload, when it has one (a full installer run with /uninstall). + public static string? PayloadProduct() + { + try + { + using var payload = PayloadReader.OpenCurrentProcess(); + return payload.Manifest.Product; + } + catch (PayloadException) + { + return null; + } + } + + private static async Task CloseProgramsAsync(string directory, IEnumerable programs) + { + var running = RunningPrograms.Find(directory, programs); + if (running.Count == 0) return true; + Log.Info("setup", $"Asking {RunningPrograms.Describe(running)} to close"); + var still = await RunningPrograms.CloseAsync(running, CloseTimeout).ConfigureAwait(false); + foreach (var p in running) p.Dispose(); + return still.Count == 0; + } +} diff --git a/src/Titano.Setup/Engine/UninstallEngine.cs b/src/Titano.Setup/Engine/UninstallEngine.cs new file mode 100644 index 00000000..d793b225 --- /dev/null +++ b/src/Titano.Setup/Engine/UninstallEngine.cs @@ -0,0 +1,106 @@ +using System.IO; +using Titano.Core.Diagnostics; +using Titano.Core.Packaging; +using Titano.Setup.Cli; +using Titano.Setup.Interop; + +namespace Titano.Setup.Engine; + +/// An installation found on disk: its folder and log. +internal sealed record InstalledProduct(string Directory, InstallLog Log); + +/// +/// Removes an installation using only its log: shortcuts, file types, logged files, the log and the Add/Remove +/// Programs entry, then the uninstaller itself. Files the log does not list are left alone; the user data folder +/// is deleted only when removeUserData is set by an explicit choice in the window. +/// +internal static class UninstallEngine +{ + /// The installation to remove: /DIR, the uninstaller's own folder, or the registered location. + public static InstalledProduct? Locate(string? directory, string? productFromPayload) + { + var candidates = new List { directory, Path.GetDirectoryName(Environment.ProcessPath) }; + if (productFromPayload is not null) candidates.Add(SetupRegistry.FindInstall(SetupPaths.ProductKey(productFromPayload))?.Directory); + foreach (var candidate in candidates) + { + if (string.IsNullOrEmpty(candidate)) continue; + if (InstallLog.TryLoad(candidate) is { } log) return new InstalledProduct(Path.GetFullPath(candidate), log); + } + return null; + } + + public static void Uninstall(InstalledProduct product, bool removeUserData, IProgress? progress) + { + var (directory, log) = product; + Log.Info("setup", $"Removing {log.Product} {log.Version} from '{directory}' (remove data: {removeUserData})"); + // First, so that a failure here leaves the program installed and the uninstaller able to retry. + if (removeUserData && Directory.Exists(SetupPaths.UserData)) + { + Log.Info("setup", $"Removing user data '{SetupPaths.UserData}' at the user's request"); + Directory.Delete(SetupPaths.UserData, recursive: true); + } + foreach (var link in log.Shortcuts) DeleteShortcut(link, log.Scope); + progress?.Report(new SetupProgress(0.1, string.Empty)); + + var fileTypes = log.Associations.Where(a => SetupRegistry.IsValidFileType(a.Extension, a.ProgId)).ToList(); + foreach (var a in fileTypes) SetupRegistry.UnregisterFileType(log.Scope, a.Extension, a.ProgId); + if (fileTypes.Count > 0) NativeMethods.NotifyAssociationsChanged(); + progress?.Report(new SetupProgress(0.2, string.Empty)); + + var failed = InstalledFiles.Remove(directory, log.Files.Where(PayloadPath.IsValid)); + progress?.Report(new SetupProgress(0.8, string.Empty)); + if (failed.Count > 0) + { + // Keep the entry and a log of what is left, so the user can run the uninstaller again. + log.Files = [.. failed]; + log.Shortcuts = []; + log.Associations = []; + log.Save(directory); + throw new SetupException(SetupExitCode.Failed, $"{failed.Count} file(s) could not be removed."); + } + + SetupRegistry.DeleteUninstallEntry(log.Scope, log.ProductKey); + File.Delete(Path.Combine(directory, InstallLog.FileName)); + var uninstaller = Path.Combine(directory, log.UninstallerName); + try + { + if (Environment.ProcessPath is { } self && Path.GetFullPath(self).Equals(Path.GetFullPath(uninstaller), StringComparison.OrdinalIgnoreCase)) + { + SelfCleanup.Schedule(uninstaller); + } + else + { + if (File.Exists(uninstaller)) File.Delete(uninstaller); + InstalledFiles.Remove(directory, [], removeEmptyRoot: true); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.ComponentModel.Win32Exception) + { + // Everything else is gone; a leftover uninstaller is not worth failing the removal. + Log.Warning("setup", $"Uninstaller '{uninstaller}' not removed", ex); + } + progress?.Report(new SetupProgress(1, string.Empty)); + } + + /// Deletes a shortcut recorded in a log, but only a .lnk directly in the Start menu or desktop folder. + public static void DeleteShortcut(string link, InstallScope scope) + { + var folder = Path.GetDirectoryName(link); + var allowed = folder is not null && link.EndsWith(".lnk", StringComparison.OrdinalIgnoreCase) + && (folder.Equals(SetupPaths.StartMenu(scope), StringComparison.OrdinalIgnoreCase) + || folder.Equals(SetupPaths.Desktop(scope), StringComparison.OrdinalIgnoreCase)); + if (!allowed) + { + Log.Warning("setup", $"Ignoring shortcut outside the shortcut folders: '{link}'"); + return; + } + try + { + File.Delete(link); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Log.Warning("setup", $"Shortcut '{link}' not removed", ex); + } + } +} diff --git a/src/Titano.Setup/Interop/FolderPicker.cs b/src/Titano.Setup/Interop/FolderPicker.cs new file mode 100644 index 00000000..cc77e7e5 --- /dev/null +++ b/src/Titano.Setup/Interop/FolderPicker.cs @@ -0,0 +1,129 @@ +using System.IO; +using System.Runtime.InteropServices; + +namespace Titano.Setup.Interop; + +/// The Windows folder picker: IFileOpenDialog with FOS_PICKFOLDERS (no WinForms). +internal static class FolderPicker +{ + private const uint FOS_PICKFOLDERS = 0x20; + private const uint FOS_FORCEFILESYSTEM = 0x40; + private const uint FOS_PATHMUSTEXIST = 0x800; + private const uint SIGDN_FILESYSPATH = 0x80058000; + + /// Shows the picker owned by ; returns the chosen folder or null when cancelled. + public static string? Pick(IntPtr owner, string title, string? initialFolder) + { + var dialog = (IFileOpenDialog)new FileOpenDialogObject(); + try + { + dialog.GetOptions(out var options); + dialog.SetOptions(options | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST); + dialog.SetTitle(title); + if (NearestExisting(initialFolder) is { } start && TryCreateItem(start) is { } item) + { + dialog.SetFolder(item); + Marshal.ReleaseComObject(item); + } + var hr = dialog.Show(owner); + if (hr == NativeMethods.HRESULT_ERROR_CANCELLED) return null; + Marshal.ThrowExceptionForHR(hr); + dialog.GetResult(out var result); + try + { + result.GetDisplayName(SIGDN_FILESYSPATH, out var path); + return path; + } + finally + { + Marshal.ReleaseComObject(result); + } + } + finally + { + Marshal.FinalReleaseComObject(dialog); + } + } + + private static string? NearestExisting(string? folder) + { + try + { + for (var dir = folder; !string.IsNullOrEmpty(dir); dir = Path.GetDirectoryName(dir)) + { + if (Directory.Exists(dir)) return dir; + } + } + catch (ArgumentException) + { + } + return null; + } + + private static IShellItem? TryCreateItem(string path) + { + try + { + return SHCreateItemFromParsingName(path, IntPtr.Zero, typeof(IShellItem).GUID); + } + catch (COMException) + { + return null; + } + } + + [DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)] + [return: MarshalAs(UnmanagedType.Interface)] + private static extern IShellItem SHCreateItemFromParsingName(string path, IntPtr bindContext, [MarshalAs(UnmanagedType.LPStruct)] Guid riid); + + [ComImport] + [Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")] + private class FileOpenDialogObject; + + /// IModalWindow → IFileDialog → IFileOpenDialog, flattened in vtable order. + [ComImport] + [Guid("D57C7288-D4AD-4768-BE02-9D969532D960")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IFileOpenDialog + { + [PreserveSig] + int Show(IntPtr parent); + void SetFileTypes(uint count, IntPtr filterSpec); + void SetFileTypeIndex(uint index); + void GetFileTypeIndex(out uint index); + void Advise(IntPtr events, out uint cookie); + void Unadvise(uint cookie); + void SetOptions(uint options); + void GetOptions(out uint options); + void SetDefaultFolder(IShellItem item); + void SetFolder(IShellItem item); + void GetFolder(out IShellItem item); + void GetCurrentSelection(out IShellItem item); + void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string name); + void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string name); + void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title); + void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string text); + void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string label); + void GetResult(out IShellItem item); + void AddPlace(IShellItem item, int place); + void SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string extension); + void Close(int hr); + void SetClientGuid(in Guid guid); + void ClearClientData(); + void SetFilter(IntPtr filter); + void GetResults(out IntPtr items); + void GetSelectedItems(out IntPtr items); + } + + [ComImport] + [Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellItem + { + void BindToHandler(IntPtr bindContext, in Guid handler, in Guid riid, out IntPtr result); + void GetParent(out IShellItem parent); + void GetDisplayName(uint sigdn, [MarshalAs(UnmanagedType.LPWStr)] out string name); + void GetAttributes(uint mask, out uint attributes); + void Compare(IShellItem other, uint hint, out int order); + } +} diff --git a/src/Titano.Setup/Interop/NativeMethods.cs b/src/Titano.Setup/Interop/NativeMethods.cs new file mode 100644 index 00000000..e710bcfb --- /dev/null +++ b/src/Titano.Setup/Interop/NativeMethods.cs @@ -0,0 +1,57 @@ +using System.Runtime.InteropServices; + +namespace Titano.Setup.Interop; + +/// Win32 entry points used by setup (shell notification, delayed delete, process image path). +internal static partial class NativeMethods +{ + public const int ERROR_CANCELLED = 1223; + public const int HRESULT_ERROR_CANCELLED = unchecked((int)0x800704C7); + + private const int SHCNE_ASSOCCHANGED = 0x08000000; + private const int SHCNF_IDLIST = 0x0000; + private const int MOVEFILE_DELAY_UNTIL_REBOOT = 0x4; + private const int PROCESS_QUERY_LIMITED_INFORMATION = 0x1000; + + /// Tells Explorer that file associations changed so icons and "open with" refresh. + public static void NotifyAssociationsChanged() => SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero); + + /// Asks Windows to delete a file or empty folder at the next restart (needs administrator rights). + public static bool DeleteAtReboot(string path) => MoveFileExW(path, null, MOVEFILE_DELAY_UNTIL_REBOOT); + + /// Full path of the executable of process , or null when it cannot be queried. + public static unsafe string? ProcessImagePath(int processId) + { + var handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, processId); + if (handle == IntPtr.Zero) return null; + try + { + const int capacity = 1024; + var buffer = stackalloc char[capacity]; + var length = capacity; + return QueryFullProcessImageNameW(handle, 0, buffer, ref length) ? new string(buffer, 0, length) : null; + } + finally + { + CloseHandle(handle); + } + } + + [LibraryImport("shell32.dll")] + private static partial void SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2); + + [LibraryImport("kernel32.dll", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool MoveFileExW(string existingFileName, string? newFileName, int flags); + + [LibraryImport("kernel32.dll", SetLastError = true)] + private static partial IntPtr OpenProcess(int desiredAccess, [MarshalAs(UnmanagedType.Bool)] bool inheritHandle, int processId); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static unsafe partial bool QueryFullProcessImageNameW(IntPtr process, int flags, char* exeName, ref int size); + + [LibraryImport("kernel32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool CloseHandle(IntPtr handle); +} diff --git a/src/Titano.Setup/Interop/ShellLink.cs b/src/Titano.Setup/Interop/ShellLink.cs new file mode 100644 index 00000000..6f033480 --- /dev/null +++ b/src/Titano.Setup/Interop/ShellLink.cs @@ -0,0 +1,61 @@ +using System.IO; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; + +namespace Titano.Setup.Interop; + +/// Creates .lnk shortcuts through the shell's IShellLinkW and IPersistFile COM interfaces. +internal static class ShellLink +{ + /// Writes a shortcut at that starts in its own folder. + public static void Create(string linkPath, string target, string description) + { + StaThread.Run(() => + { + var link = (IShellLinkW)new ShellLinkObject(); + try + { + link.SetPath(target); + link.SetWorkingDirectory(Path.GetDirectoryName(target)!); + link.SetIconLocation(target, 0); + link.SetDescription(description); + Directory.CreateDirectory(Path.GetDirectoryName(linkPath)!); + ((IPersistFile)link).Save(linkPath, true); + } + finally + { + Marshal.FinalReleaseComObject(link); + } + }); + } + + [ComImport] + [Guid("00021401-0000-0000-C000-000000000046")] + private class ShellLinkObject; + + /// Vtable-ordered declaration; only the setters are called, so getters take raw pointers. + [ComImport] + [Guid("000214F9-0000-0000-C000-000000000046")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellLinkW + { + void GetPath(IntPtr file, int maxPath, IntPtr findData, uint flags); + void GetIDList(out IntPtr idList); + void SetIDList(IntPtr idList); + void GetDescription(IntPtr name, int maxName); + void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string name); + void GetWorkingDirectory(IntPtr dir, int maxPath); + void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string dir); + void GetArguments(IntPtr args, int maxPath); + void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string args); + void GetHotkey(out short hotkey); + void SetHotkey(short hotkey); + void GetShowCmd(out int showCmd); + void SetShowCmd(int showCmd); + void GetIconLocation(IntPtr iconPath, int maxIconPath, out int icon); + void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string iconPath, int icon); + void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string relativePath, int reserved); + void Resolve(IntPtr hwnd, int flags); + void SetPath([MarshalAs(UnmanagedType.LPWStr)] string file); + } +} diff --git a/src/Titano.Setup/Interop/StaThread.cs b/src/Titano.Setup/Interop/StaThread.cs new file mode 100644 index 00000000..a32a78f7 --- /dev/null +++ b/src/Titano.Setup/Interop/StaThread.cs @@ -0,0 +1,33 @@ +using System.Runtime.ExceptionServices; +using System.Threading; + +namespace Titano.Setup.Interop; + +/// Runs work on a short-lived single-threaded apartment, as the apartment-threaded shell COM objects expect. +internal static class StaThread +{ + public static void Run(Action action) + { + if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) + { + action(); + return; + } + ExceptionDispatchInfo? failure = null; + var thread = new Thread(() => + { + try + { + action(); + } + catch (Exception ex) + { + failure = ExceptionDispatchInfo.Capture(ex); + } + }); + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + thread.Join(); + failure?.Throw(); + } +} diff --git a/src/Titano.Setup/Program.cs b/src/Titano.Setup/Program.cs new file mode 100644 index 00000000..0b8fb35c --- /dev/null +++ b/src/Titano.Setup/Program.cs @@ -0,0 +1,60 @@ +using System.Globalization; +using Titano.Core.Diagnostics; +using Titano.Core.Localization; +using Titano.Setup.Cli; +using Titano.Setup.Engine; + +namespace Titano.Setup; + +/// +/// Entry point. Silent mode and the uninstaller cleanup helper run without WPF; the interactive window is the +/// . The return value is the process exit code (). +/// +internal static class Program +{ + [STAThread] + public static int Main(string[] args) + { + using var log = new FileLogSink(SetupPaths.LogDirectory, "setup"); + Log.SetSink(log); + Log.Info("setup", $"Titano.Setup {typeof(Program).Assembly.GetName().Version} {string.Join(' ', args)}"); + + SetupArguments arguments; + try + { + arguments = SetupArguments.Parse(args); + } + catch (ArgumentException ex) + { + Log.Error("setup", ex.Message); + return (int)SetupExitCode.InvalidArguments; + } + ApplyLanguage(arguments.Language); + + if (arguments.CleanupTarget is { } uninstaller) return (int)SelfCleanup.Run(uninstaller, arguments.WaitProcessId); + if (arguments.Silent) return (int)SilentSetup.RunAsync(arguments).GetAwaiter().GetResult(); + + return new App(arguments).Run(); + } + + /// Sets the UI language: the requested code, else the best match for the Windows display language. + public static void ApplyLanguage(string? code) + { + var requested = CultureInfo.CurrentUICulture; + if (code is not null) + { + try + { + requested = CultureInfo.GetCultureInfo(code); + } + catch (CultureNotFoundException) + { + Log.Warning("setup", $"Unknown language '{code}'"); + } + } + var culture = Languages.BestMatch(requested); + CultureInfo.DefaultThreadCurrentUICulture = culture; + CultureInfo.CurrentUICulture = culture; + Loc.SetCulture(culture); + } +} diff --git a/src/Titano.Setup/Titano.Setup.csproj b/src/Titano.Setup/Titano.Setup.csproj index 4aa167fd..f18d0311 100644 --- a/src/Titano.Setup/Titano.Setup.csproj +++ b/src/Titano.Setup/Titano.Setup.csproj @@ -7,6 +7,12 @@ Titano.Setup app.manifest titano + + Titano.Setup.Program + + + + true diff --git a/src/Titano.Setup/Views/ComponentOption.cs b/src/Titano.Setup/Views/ComponentOption.cs new file mode 100644 index 00000000..062ba257 --- /dev/null +++ b/src/Titano.Setup/Views/ComponentOption.cs @@ -0,0 +1,49 @@ +using Titano.Core.Localization; +using Titano.Core.Packaging; +using Titano.Ui.Mvvm; + +namespace Titano.Setup.Views; + +/// A component checkbox: localized name and tooltip (falling back to the manifest), size and selection. +internal sealed class ComponentOption(PayloadComponent component, bool selected, Action changed) : LocalizedViewModel +{ + private bool _selected = selected; + + public string Id => component.Id; + + public string Name => Loc.Get("Setup.Component." + component.Id, Loc.Culture) ?? component.DisplayName; + + public string ToolTip => Loc.Get("Tooltips.Setup.Component." + component.Id, Loc.Culture) ?? Loc.L("Tooltips.Setup.Component"); + + public string SizeText => ByteSize.Format(component.EstimatedSize); + + public bool IsSelected + { + get => _selected; + set + { + if (Set(ref _selected, value)) changed(); + } + } +} + +/// Language offered in the picker. +internal sealed record LanguageOption(string Code, string Name); + +/// Decimal byte sizes as Explorer shows them for drives ("1.5 MB"). +internal static class ByteSize +{ + private static readonly string[] Units = ["B", "KB", "MB", "GB", "TB"]; + + public static string Format(long bytes) + { + double value = bytes; + var unit = 0; + while (value >= 1000 && unit < Units.Length - 1) + { + value /= 1000; + unit++; + } + return value.ToString(unit == 0 || value >= 100 ? "0" : "0.#", Loc.Culture) + " " + Units[unit]; + } +} diff --git a/src/Titano.Setup/Views/SetupViewModel.cs b/src/Titano.Setup/Views/SetupViewModel.cs new file mode 100644 index 00000000..1b6d4aee --- /dev/null +++ b/src/Titano.Setup/Views/SetupViewModel.cs @@ -0,0 +1,514 @@ +using System.Collections; +using System.ComponentModel; +using System.IO; +using System.Windows.Input; +using Titano.Core.Diagnostics; +using Titano.Core.Localization; +using Titano.Core.Packaging; +using Titano.Setup.Cli; +using Titano.Setup.Engine; +using Titano.Ui.Mvvm; + +namespace Titano.Setup.Views; + +/// What the setup screen currently shows. +internal enum SetupStage +{ + Options, + Confirm, + Working, + Done, + Failed, +} + +/// +/// The single setup screen for install and uninstall: options, a prompt when installed programs must close, +/// progress, success and failure. Work runs on the thread pool and reports through . +/// +internal sealed class SetupViewModel : LocalizedViewModel, INotifyDataErrorInfo +{ + private const string FallbackProduct = "Titano"; + private readonly SetupArguments _arguments; + private readonly PayloadReader? _payload; + private readonly InstallEngine? _engine; + private readonly InstallPlan? _plan; + private readonly InstalledProduct? _installed; + private readonly string _product; + private readonly string? _version; + private SetupStage _stage; + private string _directory = string.Empty; + private bool _allUsers; + private bool _desktop; + private bool _startMenu; + private bool _launchAfter; + private bool _removeUserData; + private bool _closeConfirmed; + private double _progress; + private bool _indeterminate; + private string _progressFile = string.Empty; + private string _runningPrograms = string.Empty; + private SetupExitCode _failure; + private bool _accessDenied; + private string? _launchProgram; + private Func? _operation; + + private SetupViewModel(SetupArguments arguments, string product, string? version, PayloadReader? payload, InstalledProduct? installed) + { + _arguments = arguments; + _product = product; + _version = version; + _payload = payload; + _installed = installed; + if (payload is not null) + { + _engine = new InstallEngine(payload); + _plan = InstallPlan.Resolve(_engine.Manifest, arguments); + _directory = _plan.Directory; + _allUsers = _plan.Scope == InstallScope.AllUsers; + } + _desktop = !arguments.NoDesktopShortcut; + _startMenu = !arguments.NoStartMenu; + _launchAfter = arguments.Launch; + Components = _engine is null + ? [] + : [.. _engine.Manifest.Components.Select(c => new ComponentOption(c, _plan!.Components.Contains(c.Id, StringComparer.OrdinalIgnoreCase), OnComponentsChanged))]; + Languages = [.. Core.Localization.Languages.Shipped.Select(c => new LanguageOption(c, Core.Localization.Languages.NativeName(c)))]; + + PrimaryCommand = new RelayCommand(() => Start(IsUninstall ? UninstallAsync : InstallAsync), () => CanStart); + BrowseCommand = new RelayCommand(Browse, () => IsOptions && CanChangeLocation); + CloseProgramsCommand = new RelayCommand(() => + { + _closeConfirmed = true; + Start(_operation!); + }, () => IsConfirm && _operation is not null); + BackCommand = new RelayCommand(() => Stage = SetupStage.Options, () => IsConfirm); + LaunchCommand = new RelayCommand(Launch, () => CanLaunch); + CloseCommand = new RelayCommand(() => Finish(ExitCode), () => !IsWorking); + RetryCommand = new RelayCommand(() => Start(_operation!), () => CanRetry && _operation is not null); + } + + public static SetupViewModel ForInstall(SetupArguments arguments, PayloadReader payload) => + new(arguments, payload.Manifest.Product, payload.Manifest.Version, payload, null); + + public static SetupViewModel ForUninstall(SetupArguments arguments, InstalledProduct installed) => + new(arguments, installed.Log.Product, installed.Log.Version, null, installed) { Directory = installed.Directory }; + + /// A screen that can only report why setup cannot run (no payload, nothing installed…). + public static SetupViewModel ForFailure(SetupArguments arguments, SetupExitCode code) + { + var model = new SetupViewModel(arguments, SilentSetup.PayloadProduct() ?? FallbackProduct, null, null, null); + model.Fail(new SetupException(code, code.ToString())); + return model; + } + + /// Raised when setup is finished and the window should close; holds the outcome. + public event EventHandler? Finished; + + /// Raised with false to hide the window while an elevated copy works, true to show it again. + public event EventHandler? VisibilityRequested; + + public event EventHandler? ErrorsChanged; + + /// Shows the folder picker; provided by the view, which owns the window handle. + public Func? PickFolder { get; set; } + + /// Window handle that owns the administrator prompt. + public IntPtr WindowHandle { get; set; } + + public SetupExitCode ExitCode { get; private set; } = SetupExitCode.Cancelled; + + public bool IsInstall => _engine is not null; + public bool IsUninstall => _installed is not null; + + public string WindowTitle => IsUninstall ? Loc.L("Setup.Window.Uninstall", _product) : Loc.L("Setup.Window.Title", _product); + public string Heading => _product; + + public string SubHeading => _version is null + ? string.Empty + : _plan?.Existing is { Version.Length: > 0 } existing + ? Loc.L("Setup.Header.Upgrade", _version, existing.Version) + : Loc.L("Setup.Header.Version", _version); + + public IReadOnlyList Languages { get; } + + public LanguageOption SelectedLanguage + { + get => Languages.FirstOrDefault(l => l.Code.Equals(Loc.Culture.Name, StringComparison.OrdinalIgnoreCase)) ?? Languages[0]; + set + { + if (value is not null) Program.ApplyLanguage(value.Code); + } + } + + public SetupStage Stage + { + get => _stage; + private set + { + _stage = value; + OnAllPropertiesChanged(); + CommandManager.InvalidateRequerySuggested(); + } + } + + public bool IsOptions => _stage == SetupStage.Options; + public bool IsInstallOptions => IsOptions && IsInstall; + public bool IsUninstallOptions => IsOptions && IsUninstall; + public bool IsConfirm => _stage == SetupStage.Confirm; + public bool IsWorking => _stage == SetupStage.Working; + public bool IsDone => _stage == SetupStage.Done; + public bool IsFailed => _stage == SetupStage.Failed; + + // ---- Install options ---- + + public IReadOnlyList Components { get; } + + private List SelectedComponents => [.. Components.Where(c => c.IsSelected).Select(c => c.Id)]; + + public string RequiredSpaceText => _engine is null ? string.Empty : Loc.L("Setup.Space.Required", ByteSize.Format(_engine.RequiredBytes(SelectedComponents))); + + /// False when upgrading: the existing folder and scope are kept. + public bool CanChangeLocation => _plan?.Existing is null; + + public bool IsAllUsers + { + get => _allUsers; + set + { + var before = DefaultDirectory(); + if (!Set(ref _allUsers, value)) return; + OnPropertyChanged(nameof(IsJustMe)); + // Follow the scope while the folder is still the suggested one. + if (string.Equals(Path.TrimEndingDirectorySeparator(_directory), before, StringComparison.OrdinalIgnoreCase)) Directory = DefaultDirectory(); + } + } + + public bool IsJustMe + { + get => !_allUsers; + set => IsAllUsers = !value; + } + + public string Directory + { + get => _directory; + set + { + if (!Set(ref _directory, value ?? string.Empty)) return; + ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Directory))); + OnPropertyChanged(nameof(DirectoryToolTip)); + } + } + + private bool IsDirectoryValid => SetupPaths.IsUsableInstallDirectory(_directory); + + public string DirectoryToolTip => !CanChangeLocation + ? Loc.L("Tooltips.Setup.Locked") + : IsDirectoryValid ? Loc.L("Tooltips.Setup.Folder") : Loc.L("Tooltips.Setup.FolderInvalid"); + + public string JustMeToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.JustMe") : Loc.L("Tooltips.Setup.Locked"); + public string AllUsersToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.AllUsers") : Loc.L("Tooltips.Setup.Locked"); + + public bool DesktopShortcut + { + get => _desktop; + set => Set(ref _desktop, value); + } + + public bool StartMenuShortcuts + { + get => _startMenu; + set => Set(ref _startMenu, value); + } + + public bool LaunchAfter + { + get => _launchAfter; + set => Set(ref _launchAfter, value); + } + + public bool HasDesktopOption => SelectedShortcuts().Any(s => s.Desktop); + public bool HasStartMenuOption => SelectedShortcuts().Any(s => s.StartMenu); + public bool HasLaunchOption => _engine?.LaunchTarget(SelectedComponents) is not null; + + public string InstallText => CanChangeLocation ? Loc.L("Setup.Action.Install") : Loc.L("Setup.Action.Update"); + public string InstallToolTip => CanChangeLocation ? Loc.L("Tooltips.Setup.Install") : Loc.L("Tooltips.Setup.Update"); + + private bool CanStart => IsOptions && (IsUninstall || (IsInstall && IsDirectoryValid && Components.Any(c => c.IsSelected))); + + // ---- Uninstall options ---- + + public bool RemoveUserData + { + get => _removeUserData; + set => Set(ref _removeUserData, value); + } + + // ---- Confirm, progress, outcome ---- + + public string ConfirmText => Loc.L("Setup.Running.Prompt", _runningPrograms); + + public string WorkingText => IsUninstall ? Loc.L("Setup.Progress.Removing", _product) : Loc.L("Setup.Progress.Installing", _product); + + public double Progress + { + get => _progress; + private set + { + if (Set(ref _progress, value)) OnPropertyChanged(nameof(ProgressText)); + } + } + + public string ProgressText => _indeterminate ? string.Empty : _progress.ToString("P0", Loc.Culture); + + public bool IsIndeterminate + { + get => _indeterminate; + private set + { + if (Set(ref _indeterminate, value)) OnPropertyChanged(nameof(ProgressText)); + } + } + + public string ProgressFile + { + get => _progressFile; + private set => Set(ref _progressFile, value); + } + + public string DoneText => IsUninstall ? Loc.L("Setup.Done.Removed", _product) : Loc.L("Setup.Done.Installed", _product); + + public bool CanLaunch => IsDone && _launchProgram is not null; + + public string ErrorText => _failure switch + { + SetupExitCode.PayloadInvalid => Loc.L("Setup.Error.Payload"), + SetupExitCode.ElevationDeclined => Loc.L("Setup.Error.Elevation"), + SetupExitCode.ProgramRunning => Loc.L("Setup.Error.Running", _runningPrograms), + SetupExitCode.DiskFull => Loc.L("Setup.Error.DiskFull"), + SetupExitCode.NotInstalled => Loc.L("Setup.Error.NotInstalled", _product), + SetupExitCode.InvalidArguments => Loc.L("Setup.Error.Arguments"), + _ when _accessDenied => Loc.L("Setup.Error.Access"), + _ => IsUninstall ? Loc.L("Setup.Error.Uninstall") : Loc.L("Setup.Error.Install"), + }; + + public bool CanRetry => IsFailed && _failure is not (SetupExitCode.PayloadInvalid or SetupExitCode.NotInstalled or SetupExitCode.InvalidArguments); + + public ICommand PrimaryCommand { get; } + public ICommand BrowseCommand { get; } + public ICommand CloseProgramsCommand { get; } + public ICommand BackCommand { get; } + public ICommand LaunchCommand { get; } + public ICommand CloseCommand { get; } + public ICommand RetryCommand { get; } + + public bool HasErrors => IsInstall && !IsDirectoryValid; + + public IEnumerable GetErrors(string? propertyName) => + propertyName == nameof(Directory) && HasErrors ? new[] { Loc.L("Tooltips.Setup.FolderInvalid") } : Array.Empty(); + + /// Called once the window is visible: an elevated copy continues the install the user already started. + public void OnShown() + { + if (_arguments.Elevated && IsInstall && CanStart) Start(InstallAsync); + } + + public override void Dispose() + { + foreach (var c in Components) c.Dispose(); + _payload?.Dispose(); + base.Dispose(); + } + + private void Start(Func operation) + { + _operation = operation; + _ = operation(); + } + + private async Task InstallAsync() + { + var engine = _engine!; + try + { + var request = new InstallRequest( + Path.TrimEndingDirectorySeparator(Path.GetFullPath(_directory)), + _allUsers ? InstallScope.AllUsers : InstallScope.CurrentUser, + SelectedComponents, + HasDesktopOption && _desktop, + HasStartMenuOption && _startMenu); + var target = engine.LaunchTarget(request.Components); + var program = target is null ? null : PayloadPath.Resolve(request.Directory, target); + var launch = _launchAfter ? program : null; + + if (request.Scope == InstallScope.AllUsers && !Elevation.IsElevated) + { + await InstallElevatedAsync(request, launch); + return; + } + if (!await EnsureProgramsClosedAsync(request.Directory, InstallPlan.Programs(engine.Manifest, request.Directory))) return; + + BeginWork(indeterminate: false); + var progress = new Progress(ReportProgress); + await Task.Run(() => engine.Install(request, progress, CancellationToken.None)); + _launchProgram = program; + Complete(); + if (launch is not null) Launch(); + } + catch (Exception ex) + { + Fail(ex); + } + } + + /// All users without administrator rights: an elevated copy installs with the chosen options. + private async Task InstallElevatedAsync(InstallRequest request, string? launch) + { + if (_arguments.Elevated) throw new SetupException(SetupExitCode.ElevationDeclined, "Still not elevated after relaunch."); + var switches = new SetupArguments + { + Directory = request.Directory, + Components = request.Components, + AllUsers = true, + NoDesktopShortcut = !request.DesktopShortcuts, + NoStartMenu = !request.StartMenuShortcuts, + Launch = launch is not null, + Language = Loc.Culture.Name, + }; + var child = Elevation.Start(switches, WindowHandle) ?? throw new SetupException(SetupExitCode.ElevationDeclined, "Administrator approval declined."); + VisibilityRequested?.Invoke(this, false); + Finish(await Elevation.WaitAsync(child, launch)); + } + + private async Task UninstallAsync() + { + var installed = _installed!; + try + { + if (!await EnsureProgramsClosedAsync(installed.Directory, installed.Log.Files)) return; + BeginWork(indeterminate: false); + var progress = new Progress(ReportProgress); + var removeData = _removeUserData; + await Task.Run(() => UninstallEngine.Uninstall(installed, removeData, progress)); + Complete(); + } + catch (Exception ex) + { + Fail(ex); + } + } + + /// + /// True when no installed program runs from . Otherwise the first call asks the user + /// (Confirm stage); after "Close programs" the programs are asked to close and the operation continues. + /// + private async Task EnsureProgramsClosedAsync(string directory, IEnumerable programs) + { + var running = RunningPrograms.Find(directory, programs); + try + { + if (running.Count == 0) return true; + _runningPrograms = RunningPrograms.Describe(running); + if (!_closeConfirmed) + { + Stage = SetupStage.Confirm; + return false; + } + _closeConfirmed = false; + BeginWork(indeterminate: true); + var still = await RunningPrograms.CloseAsync(running, SilentSetup.CloseTimeout); + if (still.Count == 0) return true; + _runningPrograms = RunningPrograms.Describe(still); + throw new SetupException(SetupExitCode.ProgramRunning, $"Still running: {_runningPrograms}"); + } + finally + { + foreach (var p in running) p.Dispose(); + } + } + + private void Browse() + { + if (PickFolder?.Invoke(_directory) is not { } folder) return; + // Choosing a parent such as D:\Apps installs into D:\Apps\, never loose files in D:\Apps. + Directory = Path.GetFileName(Path.TrimEndingDirectorySeparator(folder)).Equals(_product, StringComparison.OrdinalIgnoreCase) + ? folder + : Path.Combine(folder, _product); + } + + private void Launch() + { + if (_launchProgram is null) return; + if (_arguments.Elevated) + { + // The unelevated parent starts the program, so it does not run as administrator. + Finish(SetupExitCode.LaunchRequested); + return; + } + try + { + Launcher.Start(_launchProgram); + } + catch (Win32Exception ex) + { + Log.Warning("setup", $"Could not start '{_launchProgram}'", ex); + } + Finish(SetupExitCode.Success); + } + + private void Finish(SetupExitCode code) + { + ExitCode = code; + Finished?.Invoke(this, EventArgs.Empty); + } + + private void BeginWork(bool indeterminate) + { + Progress = 0; + ProgressFile = string.Empty; + IsIndeterminate = indeterminate; + Stage = SetupStage.Working; + } + + private void ReportProgress(SetupProgress value) + { + IsIndeterminate = false; + Progress = value.Fraction; + if (value.CurrentFile.Length > 0) ProgressFile = value.CurrentFile; + } + + private void Complete() + { + ExitCode = SetupExitCode.Success; + Stage = SetupStage.Done; + } + + private void Fail(Exception ex) + { + Log.Error("setup", IsUninstall ? "Uninstall failed" : "Install failed", ex); + _failure = SilentSetup.CodeFor(ex); + _accessDenied = ex is UnauthorizedAccessException; + ExitCode = _failure; + VisibilityRequested?.Invoke(this, true); + Stage = SetupStage.Failed; + } + + private void OnComponentsChanged() + { + OnPropertyChanged(nameof(RequiredSpaceText)); + OnPropertyChanged(nameof(HasDesktopOption)); + OnPropertyChanged(nameof(HasStartMenuOption)); + OnPropertyChanged(nameof(HasLaunchOption)); + CommandManager.InvalidateRequerySuggested(); + } + + private IEnumerable SelectedShortcuts() + { + if (_engine is null) return []; + var selected = SelectedComponents; + return _engine.Manifest.Shortcuts.Where(s => selected.Contains(s.Component, StringComparer.OrdinalIgnoreCase)); + } + + private string DefaultDirectory() => + SetupPaths.DefaultDirectory(_allUsers ? InstallScope.AllUsers : InstallScope.CurrentUser, _product); +} diff --git a/src/Titano.Setup/Views/SetupWindow.xaml b/src/Titano.Setup/Views/SetupWindow.xaml new file mode 100644 index 00000000..9b4495b6 --- /dev/null +++ b/src/Titano.Setup/Views/SetupWindow.xaml @@ -0,0 +1,152 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +