- Windows services whose program lies in the install folder (Titano.Server --install-service) are found in the registry and, through the Service Control Manager, stopped before files are replaced (they join the "programs running" prompt), started again after an upgrade that stopped them, deleted when an upgrade drops their program and on uninstall. An unelevated setup runs that step in an elevated copy (/SERVICES=...). - The Server component installs for all users only (manifest allUsersOnly): choosing it moves a new install to Program Files and disables "Just me" with the reason; a per-user install cannot take it. - Uninstall removes every HKCU Run value that starts a program in the folder (the Uploader's "Start with Windows"). - A shortcut that already starts an existing program elsewhere is neither retargeted nor logged, and a logged shortcut is deleted only while it still starts a program of this folder, so the two products no longer remove each other's "Titano Uploader" shortcuts. - "Remove my data" lists and deletes only the data of this product's programs that no other installed Titano product uses (the desktop app and the Uploader share %LOCALAPPDATA%\Titano and its logs folder). - The .titano file type is named in setup's language (Setup.FileType.*). Setup tests run in Titano.App.Tests on Windows CI. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
221 lines
10 KiB
C#
221 lines
10 KiB
C#
using System.Diagnostics.CodeAnalysis;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
using System.Text.RegularExpressions;
|
|
|
|
namespace Titano.Core.Packaging;
|
|
|
|
/// <summary>How an entry's bytes are stored in the data region.</summary>
|
|
public enum PayloadCompression
|
|
{
|
|
Stored,
|
|
Deflate,
|
|
}
|
|
|
|
/// <summary>Describes everything a TPK1 installer carries: product, components, files, shortcuts and file types.</summary>
|
|
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<PayloadComponent> Components { get; init; } = [];
|
|
public List<PayloadFile> Files { get; init; } = [];
|
|
public List<PayloadShortcut> Shortcuts { get; init; } = [];
|
|
public List<PayloadAssociation> Associations { get; init; } = [];
|
|
|
|
/// <summary>The component with <paramref name="id"/> (ordinal, case-insensitive), or null.</summary>
|
|
public PayloadComponent? FindComponent(string id) =>
|
|
Components.FirstOrDefault(c => c.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
|
|
|
|
/// <summary>
|
|
/// Files installed by the given components, one entry per path in manifest order. A path shared by several
|
|
/// components (identical content, enforced by <see cref="Validate"/>) is listed once.
|
|
/// </summary>
|
|
public IReadOnlyList<PayloadFile> FilesFor(IEnumerable<string> componentIds)
|
|
{
|
|
var selected = new HashSet<string>(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<string>(PayloadPath.Comparer);
|
|
var result = new List<PayloadFile>();
|
|
foreach (var file in Files)
|
|
{
|
|
if (selected.Contains(file.Component) && seen.Add(file.Path)) result.Add(file);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
/// <summary>Rejects manifests that are inconsistent with themselves or with a data region of <paramref name="dataLength"/> bytes.</summary>
|
|
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<string>(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<string, PayloadFile>(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()));
|
|
}
|
|
|
|
/// <summary>Serializes with a fixed property order and no whitespace, so identical inputs give identical bytes.</summary>
|
|
public byte[] ToJsonBytes() => JsonSerializer.SerializeToUtf8Bytes(this, PayloadJson.Default.PayloadManifest);
|
|
|
|
/// <summary>Parses manifest bytes; malformed JSON is reported as <see cref="PayloadError.Corrupt"/>.</summary>
|
|
public static PayloadManifest Parse(ReadOnlySpan<byte> 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();
|
|
}
|
|
|
|
/// <summary>A selectable part of the product (Titano, Uploader, Server).</summary>
|
|
public sealed class PayloadComponent
|
|
{
|
|
public required string Id { get; init; }
|
|
public required string DisplayName { get; init; }
|
|
public bool DefaultSelected { get; init; }
|
|
|
|
/// <summary>Installed size in bytes (sum of the component's files).</summary>
|
|
public long EstimatedSize { get; init; }
|
|
|
|
/// <summary>
|
|
/// Installs only for all users (Program Files): the component runs as a Windows service under LocalSystem, which
|
|
/// must not start a program from a folder its user can write to.
|
|
/// </summary>
|
|
public bool AllUsersOnly { get; init; }
|
|
}
|
|
|
|
/// <summary>One installed file and where its bytes live in the data region.</summary>
|
|
public sealed class PayloadFile
|
|
{
|
|
/// <summary>Canonical relative path (<see cref="PayloadPath"/>).</summary>
|
|
public required string Path { get; init; }
|
|
public required string Component { get; init; }
|
|
public long Size { get; init; }
|
|
|
|
/// <summary>Lower-case hex SHA-256 of the uncompressed content.</summary>
|
|
public required string Sha256 { get; init; }
|
|
public PayloadCompression Compression { get; init; }
|
|
|
|
/// <summary>Offset of the stored bytes, relative to the start of the data region.</summary>
|
|
public long Offset { get; init; }
|
|
|
|
/// <summary>Number of stored (possibly compressed) bytes.</summary>
|
|
public long Length { get; init; }
|
|
|
|
/// <summary>Last write time, Unix epoch seconds (UTC).</summary>
|
|
public long ModifiedUnixSeconds { get; init; }
|
|
}
|
|
|
|
/// <summary>A shortcut to one of a component's files, created in the Start menu and/or on the desktop.</summary>
|
|
public sealed class PayloadShortcut
|
|
{
|
|
public required string Component { get; init; }
|
|
|
|
/// <summary>File name of the shortcut without <c>.lnk</c>.</summary>
|
|
public required string Name { get; init; }
|
|
|
|
/// <summary>Payload path of the program the shortcut opens.</summary>
|
|
public required string Target { get; init; }
|
|
public bool StartMenu { get; init; }
|
|
public bool Desktop { get; init; }
|
|
}
|
|
|
|
/// <summary>A file type registered to open with one of a component's programs (<c>"target" "%1"</c>).</summary>
|
|
public sealed class PayloadAssociation
|
|
{
|
|
public required string Component { get; init; }
|
|
|
|
/// <summary>Extension including the dot, e.g. <c>.titano</c>.</summary>
|
|
public required string Extension { get; init; }
|
|
public required string ProgId { get; init; }
|
|
|
|
/// <summary>File type name shown by Explorer.</summary>
|
|
public required string Description { get; init; }
|
|
|
|
/// <summary>Payload path of the program that opens the file.</summary>
|
|
public required string Target { get; init; }
|
|
}
|
|
|
|
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true, RespectNullableAnnotations = true)]
|
|
[JsonSerializable(typeof(PayloadManifest))]
|
|
internal sealed partial class PayloadJson : JsonSerializerContext;
|