using System.Buffers;
using System.Collections.Concurrent;
using System.Globalization;
using System.Security.Cryptography;
namespace Febe.Core.Library;
/// Size and SHA-256 of a file written by .
public readonly record struct FileDigest(long Bytes, string Sha256);
/// A file safely written to its final name.
/// Path relative to the root folder, '/' separated (may differ from the one asked: never overwrites).
/// Full path on disk.
/// Size.
/// Lowercase hex SHA-256, computed while writing.
/// The modification time was set as asked.
public sealed record SavedFile(string RelativePath, string FullPath, long Bytes, string Sha256, bool LastWriteTimeSet);
/// Options of a safe write.
public sealed record SafeWriteOptions
{
/// Set the file modification time to this instant (publication time, spec §4.7). Null leaves it.
public DateTimeOffset? LastWriteTime { get; init; }
/// Abort with beyond this size (e.g. «Salta i video oltre»).
public long? MaxBytes { get; init; }
/// Bytes written so far.
public IProgress? Progress { get; init; }
///
/// The root folder must already exist: before anything is created (spec §4.10
/// «La radice di una destinazione non si crea mai»: a missing disk or share must not become a local folder).
/// Subfolders are still created. The root could vanish between the check and the creation of a subfolder: on Windows
/// a missing drive or share throws anyway, and in Docker a mount cannot vanish inside a running container.
///
public bool RequireExistingRoot { get; init; }
///
/// After the flush, read the temporary file back from the disk and compare its SHA-256 with the one computed while
/// writing, before the final name is decided (copies to external disks, spec §4.10). On a mismatch the temporary file
/// is removed and an says so.
///
public bool VerifyFromDisk { get; init; }
}
/// The content exceeded ; nothing was kept.
public sealed class FileTooLargeException : IOException
{
public FileTooLargeException()
{
}
public FileTooLargeException(string message)
: base(message)
{
}
public FileTooLargeException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/// The root folder of a write with does not exist; nothing was created.
public sealed class ExportRootMissingException : DirectoryNotFoundException
{
public ExportRootMissingException()
{
}
public ExportRootMissingException(string message)
: base(message)
{
}
public ExportRootMissingException(string message, Exception innerException)
: base(message, innerException)
{
}
}
///
/// Writes library files safely (spec §6.5 point 4, rule 12):
///
/// - the content goes to a temporary name (.febe-*.part) in the destination folder;
/// - SHA-256 is computed while writing, then the data is flushed to disk;
/// - the file is renamed to its final name; an existing file is never overwritten — a free name
/// («nome (2).jpg») is chosen instead;
/// - if anything goes wrong or the operation is cancelled, the temporary file is removed: an interrupted
/// download never leaves a file with the final name.
///
///
public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathLength)
{
/// Prefix of temporary files.
public const string TempPrefix = ".febe-";
/// Suffix of temporary files.
public const string TempSuffix = ".part";
private const int BufferSize = 128 * 1024;
private const int MaxNameAttempts = 10_000;
/// Serializes «is the name free? then rename» across all writers of the process.
private static readonly Lock MoveGate = new();
/// Temporary files this process is writing now: the clean-up of a previous run never touches them.
private static readonly ConcurrentDictionary LiveTemporaryFiles =
new(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
///
/// Marks a temporary file this process is about to write: leaves it alone
/// until the returned handle is disposed. The clean-up of an interrupted run can still be going through a large
/// library while the first downloads of this run are written (on Linux a deleted open file would be lost).
///
public static IDisposable ReserveTemporaryFile(string path)
{
ArgumentException.ThrowIfNullOrWhiteSpace(path);
var key = Path.GetFullPath(path);
LiveTemporaryFiles[key] = 0;
return new TemporaryFileReservation(key);
}
/// Writes to inside .
public Task SaveAsync(Stream source, string rootFolder, string relativePath, SafeWriteOptions? options = null, CancellationToken ct = default)
{
var segments = Segments(relativePath);
var directory = string.Join('/', segments.Take(segments.Count - 1));
var sanitized = string.Join('/', segments);
return SaveAsync(source, rootFolder, directory, _ => sanitized, options, ct);
}
///
/// Writes and decides the final name only after hashing (e.g. profile pictures, named after
/// their SHA-256). The temporary file is written in (relative to the root, '/'
/// separated; use the destination folder when known).
///
public async Task SaveAsync(
Stream source,
string rootFolder,
string tempDirectory,
Func relativePathFor,
SafeWriteOptions? options = null,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(relativePathFor);
var saved = await SaveAsync(source, rootFolder, tempDirectory, (d, _) => ValueTask.FromResult(relativePathFor(d)), options, ct)
.ConfigureAwait(false);
return saved!;
}
///
/// Writes to a temporary file, then asks — knowing size and
/// SHA-256 — for the final relative path. When returns null the content is discarded
/// (e.g. identical to a file already in the account, spec §9.5): nothing is left on disk and the result is null.
///
public async Task SaveAsync(
Stream source,
string rootFolder,
string tempDirectory,
Func> decide,
SafeWriteOptions? options = null,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(source);
ArgumentException.ThrowIfNullOrWhiteSpace(rootFolder);
ArgumentNullException.ThrowIfNull(decide);
options ??= new SafeWriteOptions();
var root = Path.GetFullPath(rootFolder);
var tempFolder = string.IsNullOrEmpty(tempDirectory) ? root : LibraryLayout.FullPath(root, tempDirectory);
if (options.RequireExistingRoot && !Directory.Exists(root))
{
throw new ExportRootMissingException($"La cartella {root} non c'è: Febe non la crea, perché un disco o una condivisione assente non deve diventare una cartella locale.");
}
Directory.CreateDirectory(tempFolder);
var tempPath = Path.Combine(tempFolder, TempPrefix + Guid.NewGuid().ToString("N")[..12] + TempSuffix);
using var reservation = ReserveTemporaryFile(tempPath);
try
{
var digest = await WriteTempAsync(source, tempPath, options, ct).ConfigureAwait(false);
ct.ThrowIfCancellationRequested();
if (options.VerifyFromDisk)
{
await VerifyFromDiskAsync(tempPath, digest, ct).ConfigureAwait(false);
}
var desired = await decide(digest, ct).ConfigureAwait(false);
if (desired is null)
{
return null;
}
ct.ThrowIfCancellationRequested();
var finalPath = MoveToFreeName(tempPath, root, desired, out var relative);
var timeSet = true;
if (options.LastWriteTime is { } time)
{
try
{
File.SetLastWriteTimeUtc(finalPath, time.UtcDateTime);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentOutOfRangeException)
{
timeSet = false; // some shares refuse it: the file is still good
}
}
return new SavedFile(relative, finalPath, digest.Bytes, digest.Sha256, timeSet);
}
finally
{
TryDelete(tempPath); // no-op after a successful move
}
}
///
/// Removes temporary files left by an interrupted process (never library files: only .febe-*.part), except
/// those this process is writing (). Returns how many were removed.
///
public static int CleanupTemporaryFiles(string folder, bool recursive = true)
{
if (!Directory.Exists(folder))
{
return 0;
}
var removed = 0;
var files = Directory.EnumerateFiles(
folder,
TempPrefix + "*" + TempSuffix,
new EnumerationOptions { RecurseSubdirectories = recursive, IgnoreInaccessible = true, AttributesToSkip = 0 });
foreach (var file in files)
{
if (LiveTemporaryFiles.ContainsKey(Path.GetFullPath(file)))
{
continue; // being written by this process right now
}
if (TryDelete(file))
{
removed++;
}
}
return removed;
}
/// True for a temporary file name of the safe writer.
public static bool IsTemporaryFile(string path)
{
var name = Path.GetFileName(path);
return name.StartsWith(TempPrefix, StringComparison.Ordinal) && name.EndsWith(TempSuffix, StringComparison.Ordinal);
}
private static async Task WriteTempAsync(Stream source, string tempPath, SafeWriteOptions options, CancellationToken ct)
{
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
var buffer = ArrayPool.Shared.Rent(BufferSize);
long total = 0;
try
{
await using var target = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, BufferSize, FileOptions.Asynchronous);
int read;
while ((read = await source.ReadAsync(buffer.AsMemory(0, BufferSize), ct).ConfigureAwait(false)) > 0)
{
total += read;
if (options.MaxBytes is { } max && total > max)
{
throw new FileTooLargeException(
string.Create(CultureInfo.InvariantCulture, $"Il file supera il limite di {max} byte: non viene salvato."));
}
hash.AppendData(buffer, 0, read);
await target.WriteAsync(buffer.AsMemory(0, read), ct).ConfigureAwait(false);
options.Progress?.Report(total);
}
await target.FlushAsync(ct).ConfigureAwait(false);
target.Flush(flushToDisk: true);
}
finally
{
ArrayPool.Shared.Return(buffer);
}
return new FileDigest(total, Convert.ToHexStringLower(hash.GetHashAndReset()));
}
/// Reads the temporary file back and compares its SHA-256 with the one computed while writing.
private static async Task VerifyFromDiskAsync(string tempPath, FileDigest digest, CancellationToken ct)
{
string onDisk;
await using (var stream = new FileStream(tempPath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan))
{
onDisk = Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false));
}
if (!string.Equals(onDisk, digest.Sha256, StringComparison.Ordinal))
{
TryDelete(tempPath); // our own temporary file: the caller's finally would remove it too
throw new IOException("La copia scritta sul disco non corrisponde: il disco potrebbe avere problemi.");
}
}
/// Sanitized segments of a relative path ('/' or '\' separated). «..» becomes «_»: nothing escapes the root.
private static List Segments(string relativePath)
{
ArgumentException.ThrowIfNullOrWhiteSpace(relativePath);
var segments = LibraryLayout.ToStored(relativePath)
.Split('/', StringSplitOptions.RemoveEmptyEntries)
.Select(WindowsFileNames.SanitizeSegment)
.ToList();
return segments.Count == 0 ? throw new ArgumentException("Il nome del file è vuoto.", nameof(relativePath)) : segments;
}
private string MoveToFreeName(string tempPath, string root, string desiredRelativePath, out string relative)
{
var segments = Segments(desiredRelativePath);
var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]);
for (var attempt = 1; attempt <= MaxNameAttempts; attempt++)
{
var name = attempt == 1 ? segments[^1] : string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}");
var candidate = segments.Take(segments.Count - 1).Append(WindowsFileNames.SanitizeSegment(name)).ToList();
var fitted = WindowsFileNames.FitPath(root, candidate, maxPathLength);
relative = string.Join('/', fitted);
var finalPath = LibraryLayout.FullPath(root, relative);
Directory.CreateDirectory(Path.GetDirectoryName(finalPath)!);
// On Unix File.Move(overwrite: false) checks for the destination and then renames, and a rename replaces:
// two writers of this process could overwrite each other. The check and the rename are therefore done under
// one lock (Febe is the only writer of its library). On Windows the move itself refuses an existing name.
lock (MoveGate)
{
if (File.Exists(finalPath) || Directory.Exists(finalPath))
{
continue;
}
try
{
File.Move(tempPath, finalPath, overwrite: false);
return finalPath;
}
catch (IOException) when (File.Exists(finalPath))
{
// Another program took the name in the meantime: try the next one.
}
}
}
throw new IOException($"Nessun nome libero per {desiredRelativePath} dopo {MaxNameAttempts} tentativi.");
}
private sealed class TemporaryFileReservation(string key) : IDisposable
{
public void Dispose() => LiveTemporaryFiles.TryRemove(key, out _);
}
private static bool TryDelete(string path)
{
try
{
if (File.Exists(path))
{
File.Delete(path);
return true;
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Best effort: a leftover temporary file is removed at the next start-up.
}
return false;
}
}