Piattaforme: istanza unica dopo lo spostamento dei dati, avvio sicuro del contenitore, rilascio con prove e immagine, accesso senza reindirizzamenti esterni (pkg-1, pkg-2, pkg-3, pkg-4, pkg-5, pkg-6, websec-2, web-8, websec-3)
Registro di casa 192.168.30.23:3000 (HTTP) nel modello Unraid, in compose e nel rilascio con buildx; profilo seccomp fuori da /dati. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
36 files changed
+1683
-152
No files matched your search
@@ -1,20 +1,34 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Desktop.Core;
|
||||
|
||||
/// <summary>
|
||||
/// «Avvia Febe all'accensione del computer» (spec §12): the value <c>Febe</c> under
|
||||
/// <c>HKCU\Software\Microsoft\Windows\CurrentVersion\Run</c>, per user, no administrator rights. Febe then starts with
|
||||
/// <c>--nascosto</c>: only the icon in the notification area, the window stays closed.
|
||||
/// «Avvia Febe all'accensione del computer» (spec §12): a value under <c>HKCU\Software\Microsoft\Windows\CurrentVersion\Run</c>,
|
||||
/// per user, no administrator rights. Febe then starts with <c>--nascosto</c>: only the icon in the notification area,
|
||||
/// the window stays closed. Each Febe has its own value: <c>Febe</c> for the usual one (Data folder recorded or
|
||||
/// default), <c>Febe-…</c> with <c>--dati</c> for one started on a Data folder of its own (a second account), so the
|
||||
/// switch of one never starts, shows or removes the other.
|
||||
/// </summary>
|
||||
public static class Autostart
|
||||
{
|
||||
/// <summary>The registry key, under HKEY_CURRENT_USER.</summary>
|
||||
public const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
|
||||
|
||||
/// <summary>The name of the value.</summary>
|
||||
/// <summary>The name of the value of the usual Febe.</summary>
|
||||
public const string ValueName = "Febe";
|
||||
|
||||
/// <summary>The command written in the value: the quoted executable and <c>--nascosto</c>.</summary>
|
||||
public static string Command(string executable)
|
||||
/// <summary>
|
||||
/// The name of the value: <see cref="ValueName"/> without a Data folder of its own, otherwise «Febe-» and the
|
||||
/// identity of the folder (the same as the single-instance guard, so the same folder always has the same value).
|
||||
/// </summary>
|
||||
public static string ValueNameFor(string? fixedDataFolder) =>
|
||||
fixedDataFolder is null ? ValueName : InstanceIdentity.For(fixedDataFolder);
|
||||
|
||||
/// <summary>
|
||||
/// The command written in the value: the quoted executable, <c>--nascosto</c> and, for a Febe started with
|
||||
/// <c>--dati</c>, the same Data folder.
|
||||
/// </summary>
|
||||
public static string Command(string executable, string? fixedDataFolder = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(executable);
|
||||
if (executable.Contains('"', StringComparison.Ordinal))
|
||||
@@ -22,43 +36,150 @@ public static class Autostart
|
||||
throw new ArgumentException("Percorso dell'eseguibile non valido.", nameof(executable));
|
||||
}
|
||||
|
||||
return $"\"{executable}\" --nascosto";
|
||||
if (fixedDataFolder is null)
|
||||
{
|
||||
return $"\"{executable}\" --nascosto";
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(fixedDataFolder) || fixedDataFolder.Contains('"', StringComparison.Ordinal))
|
||||
{
|
||||
throw new ArgumentException("Percorso della cartella dei dati non valido.", nameof(fixedDataFolder));
|
||||
}
|
||||
|
||||
return $"\"{executable}\" --nascosto --dati {Quote(fixedDataFolder)}";
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="value"/> starts this executable (a value left by another copy of Febe is not ours).</summary>
|
||||
public static bool PointsTo(string? value, string executable)
|
||||
/// <summary>
|
||||
/// True when <paramref name="value"/> starts this executable on this Data folder: <paramref name="fixedDataFolder"/>
|
||||
/// for a Febe started with <c>--dati</c>, none for the usual one. A value left by another copy of Febe, or written
|
||||
/// for another Data folder, is not ours.
|
||||
/// </summary>
|
||||
public static bool PointsTo(string? value, string executable, string? fixedDataFolder = null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value) || string.IsNullOrWhiteSpace(executable))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var text = value.Trim();
|
||||
string target;
|
||||
if (text.StartsWith('"'))
|
||||
var arguments = Split(value.Trim());
|
||||
if (arguments is not [var target, .. var rest] || !SamePath(target, executable))
|
||||
{
|
||||
var end = text.IndexOf('"', 1);
|
||||
if (end < 0)
|
||||
return false;
|
||||
}
|
||||
|
||||
string? dataFolder = null;
|
||||
for (var i = 0; i < rest.Count; i++)
|
||||
{
|
||||
if (string.Equals(rest[i], "--dati", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
if (i + 1 >= rest.Count)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
dataFolder = rest[++i];
|
||||
}
|
||||
}
|
||||
|
||||
return fixedDataFolder is null ? dataFolder is null : dataFolder is not null && SamePath(dataFolder, fixedDataFolder);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The words of a command line as Windows programs read them: blanks separate, quotes group, backslashes are plain
|
||||
/// except before a quote (2n backslashes and a quote: n backslashes and a quote that groups; 2n+1: n and a literal
|
||||
/// quote). Null for an unfinished quote.
|
||||
/// </summary>
|
||||
internal static List<string>? Split(string commandLine)
|
||||
{
|
||||
var words = new List<string>();
|
||||
var word = new StringBuilder();
|
||||
var inWord = false;
|
||||
var quoted = false;
|
||||
for (var i = 0; i < commandLine.Length; i++)
|
||||
{
|
||||
var c = commandLine[i];
|
||||
if (c == '\\')
|
||||
{
|
||||
var start = i;
|
||||
while (i < commandLine.Length && commandLine[i] == '\\')
|
||||
{
|
||||
i++;
|
||||
}
|
||||
|
||||
var count = i - start;
|
||||
if (i < commandLine.Length && commandLine[i] == '"')
|
||||
{
|
||||
word.Append('\\', count / 2);
|
||||
if (count % 2 == 1)
|
||||
{
|
||||
word.Append('"');
|
||||
}
|
||||
else
|
||||
{
|
||||
quoted = !quoted;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
word.Append('\\', count);
|
||||
i--;
|
||||
}
|
||||
|
||||
inWord = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
target = text[1..end];
|
||||
}
|
||||
else
|
||||
{
|
||||
var space = text.IndexOf(' ', StringComparison.Ordinal);
|
||||
target = space < 0 ? text : text[..space];
|
||||
if (c == '"')
|
||||
{
|
||||
quoted = !quoted;
|
||||
inWord = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!quoted && char.IsWhiteSpace(c))
|
||||
{
|
||||
if (inWord)
|
||||
{
|
||||
words.Add(word.ToString());
|
||||
word.Clear();
|
||||
inWord = false;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
word.Append(c);
|
||||
inWord = true;
|
||||
}
|
||||
|
||||
return string.Equals(Normalize(target), Normalize(executable), StringComparison.OrdinalIgnoreCase);
|
||||
if (quoted)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (inWord)
|
||||
{
|
||||
words.Add(word.ToString());
|
||||
}
|
||||
|
||||
return words;
|
||||
}
|
||||
|
||||
/// <summary>A quoted argument: backslashes before the closing quote are doubled (<c>"D:\\"</c> reads back as <c>D:\</c>).</summary>
|
||||
private static string Quote(string argument)
|
||||
{
|
||||
var trailing = argument.Length - argument.TrimEnd('\\').Length;
|
||||
return "\"" + argument + new string('\\', trailing) + "\"";
|
||||
}
|
||||
|
||||
private static bool SamePath(string a, string b) =>
|
||||
string.Equals(Normalize(a), Normalize(b), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private static string Normalize(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Path.GetFullPath(path);
|
||||
return Path.TrimEndingDirectorySeparator(Path.GetFullPath(path));
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
namespace Febe.Desktop.Core;
|
||||
|
||||
/// <summary>What <see cref="DataFolderLock.TryAcquire"/> found.</summary>
|
||||
public enum DataFolderLockOutcome
|
||||
{
|
||||
/// <summary>This Febe holds the lock: no other Febe can open the Data folder until it ends.</summary>
|
||||
Acquired,
|
||||
|
||||
/// <summary>Another Febe holds it: it is already running on this Data folder.</summary>
|
||||
HeldByAnother,
|
||||
|
||||
/// <summary>
|
||||
/// The lock file cannot be written at all (a folder that is not writable, a file in its place…): the start-up checks
|
||||
/// explain that problem, and with it Febe starts neither the engine nor the browser.
|
||||
/// </summary>
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The second guard of «one Febe at a time on a Data folder» (spec §12, rule 7): the file <c>febe.lock</c> inside the
|
||||
/// folder, open without sharing for the whole life of the process; Windows closes it when the process ends, even after a
|
||||
/// crash. The named mutex of <see cref="InstanceIdentity"/> is derived from the path, so two spellings of the same folder
|
||||
/// (a short 8.3 name, a drive letter made with <c>subst</c>, a junction) would get two names; the file is the same one.
|
||||
/// </summary>
|
||||
public sealed class DataFolderLock : IDisposable
|
||||
{
|
||||
/// <summary>The name of the lock file, inside the Data folder.</summary>
|
||||
public const string FileName = "febe.lock";
|
||||
|
||||
// Windows: ERROR_SHARING_VIOLATION, ERROR_LOCK_VIOLATION. Elsewhere .NET emulates FileShare.None with flock, which
|
||||
// answers EWOULDBLOCK (11 on Linux, 35 on macOS): only for the tests of this class, Febe.exe runs on Windows.
|
||||
private const int SharingViolation = 32;
|
||||
private const int LockViolation = 33;
|
||||
private const int WouldBlockLinux = 11;
|
||||
private const int WouldBlockMac = 35;
|
||||
|
||||
private readonly FileStream _file;
|
||||
|
||||
private DataFolderLock(FileStream file, string path)
|
||||
{
|
||||
_file = file;
|
||||
Path = path;
|
||||
}
|
||||
|
||||
/// <summary>The lock file.</summary>
|
||||
public string Path { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Takes the lock of <paramref name="dataFolder"/> (creating the folder if needed). A file held by someone else is
|
||||
/// tried again for <paramref name="patience"/> (an antivirus may look at it for a moment) before it counts as
|
||||
/// another Febe.
|
||||
/// </summary>
|
||||
public static DataFolderLockOutcome TryAcquire(string dataFolder, out DataFolderLock? acquired, TimeSpan? patience = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(dataFolder);
|
||||
acquired = null;
|
||||
var path = System.IO.Path.Combine(System.IO.Path.GetFullPath(dataFolder), FileName);
|
||||
var deadline = DateTime.UtcNow + (patience ?? TimeSpan.FromSeconds(2));
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path)!);
|
||||
var file = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, 1, FileOptions.None);
|
||||
acquired = new DataFolderLock(file, path);
|
||||
return DataFolderLockOutcome.Acquired;
|
||||
}
|
||||
catch (IOException ex) when (IsHeldElsewhere(ex))
|
||||
{
|
||||
if (DateTime.UtcNow >= deadline)
|
||||
{
|
||||
return DataFolderLockOutcome.HeldByAnother;
|
||||
}
|
||||
|
||||
Thread.Sleep(200);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or ArgumentException)
|
||||
{
|
||||
return DataFolderLockOutcome.Unavailable;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() => _file.Dispose();
|
||||
|
||||
private static bool IsHeldElsewhere(IOException ex) => OperatingSystem.IsWindows()
|
||||
? (ex.HResult & 0xFFFF) is SharingViolation or LockViolation
|
||||
: ex.HResult is WouldBlockLinux or WouldBlockMac;
|
||||
}
|
||||
@@ -39,7 +39,15 @@ public enum DataFolderMoveOutcome
|
||||
}
|
||||
|
||||
/// <summary>Outcome of <see cref="DataFolderMove.ApplyPending"/>, with an Italian message for the log and a notification.</summary>
|
||||
public sealed record DataFolderMoveResult(DataFolderMoveOutcome Outcome, string DataFolder, string? Message);
|
||||
public sealed record DataFolderMoveResult(DataFolderMoveOutcome Outcome, string DataFolder, string? Message)
|
||||
{
|
||||
/// <summary>
|
||||
/// After a move, the single-instance guard of the new folder, taken before anything was written there: from now on
|
||||
/// every launch finds the new folder recorded, and must find this Febe holding it. Null when no move happened or no
|
||||
/// guard was asked for. The caller keeps it for the life of the process.
|
||||
/// </summary>
|
||||
public IDisposable? TargetGuard { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Progress of the copy: files and bytes.</summary>
|
||||
public sealed record DataFolderMoveProgress(int FilesDone, int FilesTotal, long BytesDone, long BytesTotal);
|
||||
@@ -107,7 +115,17 @@ public static class DataFolderMove
|
||||
/// <summary>
|
||||
/// Applies the move asked from Impostazioni, if any. Call it before anything opens <paramref name="current"/>.
|
||||
/// </summary>
|
||||
public static DataFolderMoveResult ApplyPending(IDataFolderLocationStore store, string current, IProgress<DataFolderMoveProgress>? progress = null, DataFolderCheck? check = null)
|
||||
/// <param name="store">Where the folder in use and the pending move are recorded.</param>
|
||||
/// <param name="current">The Data folder this Febe started on (and holds the single-instance guard of).</param>
|
||||
/// <param name="progress">Progress of the copy.</param>
|
||||
/// <param name="check">The checks of a Data folder (local disk, writable).</param>
|
||||
/// <param name="claimTarget">
|
||||
/// Takes the single-instance guard of the new folder (spec §12: one Febe at a time on a Data folder). It is taken
|
||||
/// before anything is written there, and before the new folder is recorded: a launch that reads the new folder must
|
||||
/// find this Febe, never start a second one on it. When another Febe holds it the move does not happen. A guard
|
||||
/// taken for a move that fails is given back. Null: no guard (tests of the copy alone).
|
||||
/// </param>
|
||||
public static DataFolderMoveResult ApplyPending(IDataFolderLocationStore store, string current, IProgress<DataFolderMoveProgress>? progress = null, DataFolderCheck? check = null, InstanceGuardFactory? claimTarget = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(store);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(current);
|
||||
@@ -124,6 +142,40 @@ public static class DataFolderMove
|
||||
return new DataFolderMoveResult(DataFolderMoveOutcome.Failed, from, $"La cartella dei dati non è stata spostata in {to}: {reason} Febe usa ancora {from}.");
|
||||
}
|
||||
|
||||
IDisposable? guard = null;
|
||||
if (claimTarget is not null)
|
||||
{
|
||||
guard = claimTarget(to);
|
||||
if (guard is null)
|
||||
{
|
||||
store.SetPending(null);
|
||||
return new DataFolderMoveResult(
|
||||
DataFolderMoveOutcome.Failed,
|
||||
from,
|
||||
$"La cartella dei dati non è stata spostata in {to}: un altro Febe la sta già usando. Febe usa ancora {from}.");
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var result = Move(store, from, to, progress);
|
||||
if (result.Outcome == DataFolderMoveOutcome.Failed)
|
||||
{
|
||||
guard?.Dispose();
|
||||
return result;
|
||||
}
|
||||
|
||||
return result with { TargetGuard = guard };
|
||||
}
|
||||
catch
|
||||
{
|
||||
guard?.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static DataFolderMoveResult Move(IDataFolderLocationStore store, string from, string to, IProgress<DataFolderMoveProgress>? progress)
|
||||
{
|
||||
if (!Directory.Exists(from))
|
||||
{
|
||||
// Nothing to copy (Febe never ran here): the new folder is simply used from now on.
|
||||
|
||||
@@ -47,6 +47,13 @@ public interface IDesktopShell
|
||||
|
||||
/// <summary>Moves the main window of a process (Edge) out of view, still open: never minimised (S2).</summary>
|
||||
Task HideProcessWindowAsync(int processId, CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// Ties a process Febe started (Edge) to the life of Febe.exe: Windows ends it, with the processes it opens, when
|
||||
/// Febe ends — also after a crash or «Termina attività», so that it never stays behind holding the profile and the
|
||||
/// debugging port. False when Windows refused (the process then lives on its own, as before).
|
||||
/// </summary>
|
||||
bool EndWithFebe(System.Diagnostics.Process process);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -160,7 +167,9 @@ public sealed class DesktopPlatform : IFebePlatform
|
||||
/// <summary>
|
||||
/// Edge for the last fallback of S2: the same <see cref="ChromiumProcessHost"/> as Docker, with its fixed DevTools
|
||||
/// port on 127.0.0.1, a profile of its own inside <c>Dati\browser</c> (so «Scollega» deletes both), preferences
|
||||
/// with password saving and autofill off, and the switches of S2.
|
||||
/// with password saving and autofill off, and the switches of S2. Every Edge started is tied to the life of
|
||||
/// Febe.exe (<see cref="IDesktopShell.EndWithFebe"/>): an Edge left behind by a crash would keep the port, and every
|
||||
/// later start would find it «occupata».
|
||||
/// </summary>
|
||||
private ChromiumBrowser CreateEdge(FebePlatformContext context, string executable) => new(
|
||||
new ChromiumBrowserSettings
|
||||
@@ -177,6 +186,13 @@ public sealed class DesktopPlatform : IFebePlatform
|
||||
ExtraArguments = BrowserArguments.ForEdge(),
|
||||
SessionCookie = _options.Site.SessionCookie,
|
||||
SeedProfilePreferences = true,
|
||||
ProcessStarted = process =>
|
||||
{
|
||||
if (!_shell.EndWithFebe(process))
|
||||
{
|
||||
context.Log.Warn("browser", "Windows non ha legato Edge a Febe: se Febe si chiudesse all'improvviso, Edge resterebbe aperto (chiudilo dal Gestione attività).");
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
context.Clock,
|
||||
|
||||
@@ -27,6 +27,12 @@ public static class InstanceIdentity
|
||||
public static string PipeName(string dataFolder) => For(dataFolder);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes the single-instance guard of a Data folder (on Windows the named mutex and pipe of <see cref="InstanceIdentity"/>)
|
||||
/// for this Febe; null when another Febe already holds it. Disposing the guard gives it back.
|
||||
/// </summary>
|
||||
public delegate IDisposable? InstanceGuardFactory(string dataFolder);
|
||||
|
||||
/// <summary>What a second launch asks the running Febe.</summary>
|
||||
public enum InstanceRequest
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user