// SPDX-FileCopyrightText: 2026 Progmasoft // SPDX-License-Identifier: MIT using System; using System.Collections.Generic; using System.Formats.Tar; using System.IO; using System.Linq; using System.Security.Cryptography; using LzmaNet; using Progmasoft.Tazel.Project; namespace Progmasoft.Tazel.Archive; /// /// The archive of a module, $group.$module-$version.tazel.tar.xz: the files of the module below one directory /// of that name less the extension. It is reproducible: entries are sorted, owned by no one, dated at the epoch, and /// either 0644 or, for an executable file, 0755. /// internal static class ModuleArchive { /// The extension of an archive. public const string Extension = ".tazel.tar.xz"; /// The most an archive may unpack to; a larger one is refused before it fills the disk. public const long MaxUnpackedBytes = 1L << 30; /// The most entries an archive may hold. public const int MaxEntries = 100_000; /// $group.$module-$version, the name of an archive without its extension. public static string BaseName(string group, string module, string version) => $"{group}.{module}-{version}"; /// /// The files of the module at that go into its archive: every regular file below it, less what /// starts with a dot (.tazel, .git), the directories of other modules and what /// matches. /// public static IReadOnlyList Files(string root, Func excluded) { ArgumentNullException.ThrowIfNull(excluded); var found = new List(); var ignore = Project.Ignore.IgnoreRules.For(root); Visit(new DirectoryInfo(root), ""); found.Sort(StringComparer.Ordinal); return found; void Visit(DirectoryInfo directory, string prefix) { foreach (var entry in directory.EnumerateFileSystemInfos().OrderBy(e => e.Name, StringComparer.Ordinal)) { if (entry.Name.StartsWith('.')) { continue; } var relative = prefix + entry.Name; if (ignore.Ignored(relative, entry is DirectoryInfo)) { continue; } if (entry.LinkTarget is not null) { throw new ProjectException($"{relative} is a symbolic link; an archive holds only files"); } if (entry is DirectoryInfo child) { if (!System.IO.File.Exists(Path.Combine(child.FullName, ModuleFiles.ModuleFile))) { Visit(child, relative + "/"); } } else if (!excluded(relative)) { found.Add(relative); } } } } /// Writes of the module at below . public static void Write(string root, string baseName, string archive, IReadOnlyList files) => ReproducibleArchive.Write(root, baseName, archive, files); /// /// The directory a .unpacked marker below names, or null when there is no /// marker. The marker holds one directory name that Unpack made; anything else, such as a path that leads out of the /// destination, means the state was altered, and the unpacked files are not trusted. /// public static string? FromMarker(string destination) { ArgumentNullException.ThrowIfNull(destination); var marker = Path.Combine(destination, ".unpacked"); if (!System.IO.File.Exists(marker)) { return null; } var name = System.IO.File.ReadAllText(marker).Trim(); var directory = Path.Combine(destination, Path.GetFileName(name)); return name.Length > 0 && name == Path.GetFileName(name) && name is not ("." or "..") && Directory.Exists(directory) ? directory : throw new ProjectException($"{destination} is damaged; remove it and run the command again"); } /// Writes the marker that names the unpacked directory of . public static void WriteMarker(string destination, string directory) => System.IO.File.WriteAllText(Path.Combine(destination, ".unpacked"), Path.GetFileName(directory)); /// An unpacked archive has one top directory, and the file it must hold in it. private static void CheckUnpacked(string work, [System.Diagnostics.CodeAnalysis.NotNull] string? top, string requiredFile, string shown) { if (top is null) { throw new ProjectException($"{shown} is empty"); } if (!System.IO.File.Exists(Path.Combine(work, top, requiredFile))) { throw new ProjectException($"{shown} has no {top}/{requiredFile}"); } } /// The parts of the path of an entry, which must stay inside the archive. private static string[] PartsOf(TarEntry entry, string shown) { var name = entry.Name.TrimEnd('/'); var parts = name.Split('/'); return name.Length == 0 || name.StartsWith('/') || name.Contains('\\', StringComparison.Ordinal) || parts.Any(part => part is "" or "." or "..") ? throw new ProjectException($"{shown}: '{entry.Name}' is not a path inside the archive") : parts; } /// Writes a directory or a file of the archive; anything else is refused. Returns the bytes written. private static long Extract(TarEntry entry, string target, string shown) { if (entry.EntryType == TarEntryType.Directory) { Directory.CreateDirectory(target); return 0; } if (entry.EntryType is not (TarEntryType.RegularFile or TarEntryType.V7RegularFile)) { throw new ProjectException($"{shown}: '{entry.Name}' is a {entry.EntryType}; an archive holds only files"); } // The size is checked before the bytes are written, so a huge entry is refused unwritten. if (entry.Length > MaxUnpackedBytes) { throw new ProjectException($"{shown} unpacks to more than {MaxUnpackedBytes} bytes"); } Directory.CreateDirectory(Path.GetDirectoryName(target)!); entry.ExtractToFile(target, overwrite: false); return entry.Length; } /// /// Unpacks into , which must not exist, and returns the /// directory of the module in it. Every entry must be below one top directory; links, devices, absolute paths and /// .. are refused, as are archives over or . /// public static string Unpack(string archive, string destination) => Unpack(archive, destination, ModuleFiles.ModuleFile); /// public static string Unpack(string archive, string destination, string requiredFile) { var shown = Path.GetFileName(archive); var parent = Path.GetDirectoryName(Path.GetFullPath(destination))!; Directory.CreateDirectory(parent); var work = Path.Combine(parent, $".unpack-{Guid.NewGuid():N}"); Directory.CreateDirectory(work); try { string? top = null; long total = 0; var entries = 0; using (var input = System.IO.File.OpenRead(archive)) using (var xz = new XzDecompressStream(input, new XzDecompressOptions(), leaveOpen: false)) using (var tar = new TarReader(xz)) { while (tar.GetNextEntry() is { } entry) { if (++entries > MaxEntries) { throw new ProjectException($"{shown} holds more than {MaxEntries} entries"); } var parts = PartsOf(entry, shown); top ??= parts[0]; if (parts[0] != top) { throw new ProjectException($"{shown}: '{entry.Name}' is not below {top}/"); } total += Extract(entry, Path.Combine(work, Path.Combine(parts)), shown); if (total > MaxUnpackedBytes) { throw new ProjectException($"{shown} unpacks to more than {MaxUnpackedBytes} bytes"); } } } CheckUnpacked(work, top, requiredFile, shown); Directory.Move(work, destination); return Path.Combine(destination, top); } catch (Exception error) when (error is IOException or InvalidDataException or FormatException) { throw new ProjectException($"{shown} could not be unpacked: {error.Message}", error); } finally { if (Directory.Exists(work)) { Directory.Delete(work, recursive: true); } } } } /// The SHA-256 of an archive and the .sha256sums file beside it, as sha256sum writes it. internal static class Sha256Sums { /// The SHA-256 of in lower-case hexadecimal. public static string Sha256(string file) => ReproducibleArchive.Sha256(file); /// The line of a .sha256sums file for . public static string SumsLine(string file) => ReproducibleArchive.SumsLine(file); /// /// The SHA-256 that the .sha256sums text gives for . Lines are /// <sha256> <name> or <sha256> *<name>; blank lines are skipped and any other /// line is an error. /// public static string? SumFor(string sums, string name, string shown) { ArgumentNullException.ThrowIfNull(sums); string? found = null; var number = 0; foreach (var raw in sums.Split('\n')) { number++; var line = raw.TrimEnd('\r'); if (line.Trim().Length == 0) { continue; } if (line.Length < 67 || !line[..64].All(Uri.IsHexDigit) || line[64] != ' ' || line[65] is not (' ' or '*')) { throw new ProjectException($"{shown}:{number}: not a line of sha256sum: '{line}'"); } if (line[66..] == name) { if (found is not null) { throw new ProjectException($"{shown} lists {name} twice"); } found = line[..64].ToLowerInvariant(); } } return found; } }