// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Formats.Tar;
using System.IO;
using System.Text;
using Microsoft.Build.Framework;
namespace Microsoft.Build.Tasks
{
/// <summary>
/// Represents a task that can create a tar archive from a set of files and directories.
/// </summary>
/// <include file="TaskDocumentation.xml" path="doc/TarTaskRuntime/remarks" />
[MSBuildMultiThreadableTask]
public sealed class TarFiles : TarTaskBase
{
/// <summary>
/// The metadata of a <see cref="SourceFiles"/> item that sets its path in the archive.
/// </summary>
private const string ArchivePathMetadataName = "ArchivePath";
/// <summary>
/// The metadata of a <see cref="SourceFiles"/> item that sets its octal Unix file mode.
/// </summary>
private const string UnixFileModeMetadataName = "UnixFileMode";
/// <summary>
/// The largest Unix file mode, with all permission bits and the setuid, setgid and sticky bits set (octal 7777).
/// </summary>
private const int MaxUnixFileMode = 0xFFF;
private HashSet<string>? _overwrittenArchiveAliases;
/// <summary>
/// Gets or sets the files and directories to create a tar archive from.
/// </summary>
/// <remarks>
/// <para>
/// Each item is added at the path in its <c>ArchivePath</c> metadata, for example <c>lib/net11.0/a.dll</c>, or, without
/// that metadata, at its path relative to <see cref="SourceFilesRoot"/>. An item that is a directory adds a directory
/// entry, not the directory's contents. Entries are written in the ordinal order of their paths in the archive.
/// </para>
/// <para>
/// The <c>OwnerId</c>, <c>GroupId</c>, <c>OwnerName</c> and <c>GroupName</c> metadata override the parameters of the
/// same names for an item, and the <c>UnixFileMode</c> metadata sets the permissions recorded for it as an octal mode,
/// for example <c>755</c>. An item with <c>UnixFileMode</c> but no ownership records owner and group ID <c>0</c>, like
/// <c>DeterministicTimestamp</c> does; see <c>OwnerId</c>.
/// </para>
/// <para>
/// An item that is included more than once, for example from overlapping globs, is added once. Including it again with
/// different <c>UnixFileMode</c> or ownership metadata is an error, as is storing different items at the same path, or
/// an item inside the path of a file or link.
/// </para>
/// <para>
/// The list must not be empty: like tar refusing to create an empty archive, the task reports an error. An item that is
/// the archive itself, for example from a glob that matches the archive of a previous build, is skipped.
/// </para>
/// </remarks>
[Required]
public ITaskItem[] SourceFiles { get; set; } = null!;
/// <summary>
/// Gets or sets a <see cref="ITaskItem"/> with the directory that <see cref="SourceFiles"/> are added relative to when
/// they don't have <c>ArchivePath</c> metadata. This parameter is optional.
/// </summary>
public ITaskItem? SourceFilesRoot { get; set; }
/// <inheritdoc />
private protected override bool TryResolveSources()
{
_overwrittenArchiveAliases = null;
// MSBuild reports a missing SourceFiles parameter itself and passes an empty item list as an empty array; null is
// only possible when the task is created directly.
if (SourceFiles is not { Length: > 0 })
{
Log.LogErrorWithCodeFromResources("TarFiles.ErrorNothingToArchive", DestinationFileInfo.FullName);
return false;
}
return true;
}
/// <inheritdoc />
private protected override void BeforeOverwrite()
{
string? resolvedDestination = null;
foreach (ITaskItem item in SourceFiles)
{
ReadOnlySpan<char> name = Path.GetFileName(Path.TrimEndingDirectorySeparator(item.ItemSpec.AsSpan()));
if (!name.Equals(DestinationFileInfo.Name, StringComparison.OrdinalIgnoreCase))
{
continue;
}
string path = GetSourcePath(item);
if (path == DestinationFileInfo.FullName || !File.Exists(path))
{
continue;
}
// Resolve only the directories: a file symlink or hard link is a separate entry that survives the unlink.
resolvedDestination ??= ResolveParent(DestinationFileInfo);
if (AreSameEntryPaths(ResolveParent(new FileInfo(path)), resolvedDestination))
{
(_overwrittenArchiveAliases ??= new(StringComparer.Ordinal)).Add(path);
}
}
static string ResolveParent(FileInfo file) => Path.Combine(GetResolvedDirectoryPath(file.Directory!), file.Name);
}
private string GetSourcePath(ITaskItem item) => Path.TrimEndingDirectorySeparator(TaskEnvironment.GetAbsolutePath(item.ItemSpec).GetCanonicalForm());
/// <inheritdoc />
private protected override void LogCreatingArchive(int entryCount)
=> Log.LogMessageFromResources(MessageImportance.High, "TarFiles.Comment", DestinationFileInfo.FullName, entryCount);
/// <inheritdoc />
private protected override void LogFailIfNotIncremental()
=> Log.LogErrorWithCodeFromResources("TarFiles.ErrorFailIfNotIncremental", DestinationFileInfo.FullName);
/// <inheritdoc />
private protected override void LogFailure(string message, string lockedFileMessage)
=> Log.LogErrorWithCodeFromResources("TarFiles.ErrorFailed", DestinationFileInfo.FullName, message, lockedFileMessage);
/// <summary>
/// Collects an entry for every item of <see cref="SourceFiles"/>, logging an error for any item that can't be added, and
/// sorts the entries by name using an ordinal comparison, like <see cref="TarDirectory"/>.
/// </summary>
private protected override List<ArchiveEntry> CollectEntries(TarEntryFormat format, TarOwnership? ownership)
{
string? rootPath = SourceFilesRoot is null
? null
: FileUtilities.EnsureTrailingSlash(TaskEnvironment.GetAbsolutePath(SourceFilesRoot.ItemSpec).GetCanonicalForm());
List<ArchiveEntry> entries = new(SourceFiles.Length);
foreach (ITaskItem item in SourceFiles)
{
string sourcePath = GetSourcePath(item);
// Like TarDirectory, which lists its sources before it creates the archive, never add the archive to itself. This
// can happen when the items come from a glob that also matches the archive of a previous build. TryPrepare
// has already removed it, so a case-only variant that still exists is a distinct source.
if (sourcePath == DestinationFileInfo.FullName || _overwrittenArchiveAliases?.Contains(sourcePath) == true ||
(sourcePath.Equals(DestinationFileInfo.FullName, FileUtilities.PathComparison) && !Path.Exists(sourcePath)))
{
Log.LogMessageFromResources(MessageImportance.Low, "TarFiles.DidNotAddDestinationFile", sourcePath);
continue;
}
string archivePath = item.GetMetadata(ArchivePathMetadataName);
if (archivePath.Length > 0)
{
// ArchivePath is a path inside the archive, so accept either separator on every platform.
archivePath = archivePath.Replace('\\', '/');
}
else if (rootPath is not null && sourcePath.Length > rootPath.Length && AreSameEntryPaths(rootPath, sourcePath.AsSpan(0, rootPath.Length)))
{
// Like TarDirectory, only translate the separator on Windows, where '\\' can't be part of a name.
archivePath = sourcePath.Substring(rootPath.Length);
if (Path.DirectorySeparatorChar != '/')
{
archivePath = archivePath.Replace(Path.DirectorySeparatorChar, '/');
}
}
else
{
LogCannotAddEntry(sourcePath, "TarFiles.ReasonNoArchivePath");
continue;
}
string? entryName = NormalizeArchivePath(archivePath);
if (entryName is null)
{
LogCannotAddEntry(sourcePath, "TarFiles.ReasonInvalidArchivePath", archivePath);
continue;
}
FileSystemInfo source = Directory.Exists(sourcePath) ? new DirectoryInfo(sourcePath) : new FileInfo(sourcePath);
if (!source.Exists && source.LinkTarget is null)
{
LogCannotAddEntry(sourcePath, "TarFiles.ReasonDoesNotExist");
continue;
}
if (FollowSymbolicLinks && source.LinkTarget is not null && !TryResolveFollowedLink(source, out source))
{
continue;
}
if (source is DirectoryInfo && source.LinkTarget is null)
{
entryName += "/";
}
TarOwnership? entryOwnership = ownership;
string ownerId = item.GetMetadata(nameof(OwnerId));
string groupId = item.GetMetadata(nameof(GroupId));
string ownerName = item.GetMetadata(nameof(OwnerName));
string groupName = item.GetMetadata(nameof(GroupName));
if ((ownerId.Length > 0 || groupId.Length > 0 || ownerName.Length > 0 || groupName.Length > 0)
&& !TryResolveOwnership(
ownerId.Length > 0 ? ownerId : OwnerId,
groupId.Length > 0 ? groupId : GroupId,
ownerName.Length > 0 ? ownerName : OwnerName,
groupName.Length > 0 ? groupName : GroupName,
format,
sourcePath,
out entryOwnership))
{
continue;
}
UnixFileMode? mode = null;
string modeValue = item.GetMetadata(UnixFileModeMetadataName);
if (modeValue.Length > 0)
{
if (!TryParseUnixFileMode(modeValue, out UnixFileMode parsedMode))
{
LogCannotAddEntry(sourcePath, "TarFiles.ReasonInvalidUnixFileMode", modeValue);
continue;
}
mode = parsedMode;
}
entries.Add(new ArchiveEntry(source, entryName, sourcePath, entryOwnership, mode));
}
entries.Sort(static (left, right) => string.CompareOrdinal(left.EntryName, right.EntryName));
// An item list can contain the same item more than once, for example when it's built from overlapping globs. Only
// different sources at the same path in the archive are ambiguous, including a file and a directory: the trailing
// '/' of directory names is ignored, because extracting both would replace one with the other. Sorting doesn't
// keep "lib" and "lib/" next to each other ("lib-x" sorts between them), so look the paths up instead.
Dictionary<string, ArchiveEntry> entriesByPath = new(entries.Count, StringComparer.Ordinal);
List<ArchiveEntry> uniqueEntries = new(entries.Count);
foreach (ArchiveEntry entry in entries)
{
string path = entry.EntryName.TrimEnd('/');
if (entriesByPath.TryGetValue(path, out ArchiveEntry previous))
{
if (!AreSameEntryPaths(previous.SourcePath, entry.SourcePath))
{
Log.LogErrorWithCodeFromResources("TarFiles.ErrorDuplicateArchivePath", path, previous.SourcePath, entry.SourcePath);
}
else if (previous.Ownership != entry.Ownership || previous.Mode != entry.Mode)
{
Log.LogErrorWithCodeFromResources("TarFiles.ErrorDuplicateItemWithDifferentMetadata", entry.SourcePath, path);
}
continue;
}
entriesByPath.Add(path, entry);
uniqueEntries.Add(entry);
}
// Only a directory can contain other entries: extracting an entry inside the path of a file or link fails, because
// its parent directory can't be created. TarDirectory can't produce this, but items can be stored at any path.
Dictionary<string, ArchiveEntry>.AlternateLookup<ReadOnlySpan<char>> entriesBySpan = entriesByPath.GetAlternateLookup<ReadOnlySpan<char>>();
HashSet<string>? reportedParents = null;
foreach (ArchiveEntry entry in uniqueEntries)
{
string name = entry.EntryName;
for (int i = name.IndexOf('/'); i >= 0 && i < name.Length - 1; i = name.IndexOf('/', i + 1))
{
if (entriesBySpan.TryGetValue(name.AsSpan(0, i), out ArchiveEntry parent) && !parent.EntryName.EndsWith('/'))
{
if ((reportedParents ??= new(StringComparer.Ordinal)).Add(parent.EntryName))
{
Log.LogErrorWithCodeFromResources("TarFiles.ErrorEntryInsideFile", parent.EntryName, parent.SourcePath, name.TrimEnd('/'), entry.SourcePath);
}
break;
}
}
}
return uniqueEntries;
}
/// <summary>
/// Normalizes a path inside the archive: separators are '/', and empty and "." segments are removed.
/// </summary>
/// <param name="path">The path, with '/' separators.</param>
/// <returns>
/// The normalized path, or <see langword="null"/> if the path is empty, rooted, or has ".." segments. A Windows drive
/// prefix such as "C:" is rejected on every platform, also after leading "." segments, so that a project creates the same
/// archive everywhere.
/// </returns>
private static string? NormalizeArchivePath(string path)
{
if (path.Length == 0 || path[0] == '/')
{
return null;
}
ReadOnlySpan<char> pathSpan = path.AsSpan();
StringBuilder builder = new(path.Length);
foreach (Range range in pathSpan.Split('/'))
{
ReadOnlySpan<char> segment = pathSpan[range];
if (segment.IsEmpty || segment is ".")
{
continue;
}
if (segment is ".." || (builder.Length == 0 && segment.Length >= 2 && segment[1] == ':' && char.IsAsciiLetter(segment[0])))
{
return null;
}
if (builder.Length > 0)
{
builder.Append('/');
}
builder.Append(segment);
}
return builder.Length > 0 ? builder.ToString() : null;
}
/// <summary>
/// Parses an octal Unix file mode such as <c>755</c> or <c>0644</c>, including the setuid, setgid and sticky bits.
/// </summary>
private static bool TryParseUnixFileMode(string value, out UnixFileMode mode)
{
mode = UnixFileMode.None;
int result = 0;
foreach (char c in value)
{
if (c is < '0' or > '7')
{
return false;
}
result = (result * 8) + (c - '0');
if (result > MaxUnixFileMode)
{
return false;
}
}
mode = (UnixFileMode)result;
return true;
}
}
}