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; }
///
/// 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.
///
public bool AllUsersOnly { 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;