| 1 | using System.Security; |
| 2 | |
| 3 | namespace Zipelo.Core; |
| 4 | |
| 5 | public sealed class EngineContext |
| 6 | { |
| 7 | private readonly Guid jobId; |
| 8 | private readonly ArchiveAction action; |
| 9 | private readonly IOutputTransaction output; |
| 10 | private readonly PasswordProvider passwords; |
| 11 | private readonly Action<JobState> reportState; |
| 12 | private readonly CancellationTokenSource cancellation; |
| 13 | private readonly int maxPasswordAttempts; |
| 14 | private readonly SemaphoreSlim serial = new(1, 1); |
| 15 | private readonly SemaphoreSlim passwordSerial = new(1, 1); |
| 16 | private readonly object passwordStateGate = new(); |
| 17 | private bool waitingForPassword; |
| 18 | private readonly HashSet<string> entryIds = new(StringComparer.Ordinal); |
| 19 | private readonly HashSet<string> paths = new(OutputPathPolicy.Comparer(OutputPathPolicy.CurrentPolicy)); |
| 20 | private readonly List<EntryResult> results = []; |
| 21 | private int passwordAttempts; |
| 22 | private ArchiveError failure; |
| 23 | |
| 24 | internal EngineContext(Guid jobId, ArchiveAction action, JobBudget budget, IOutputTransaction output, |
| 25 | PasswordProvider passwords, Action<JobState> reportState, CancellationTokenSource cancellation, int maxPasswordAttempts) |
| 26 | { |
| 27 | this.jobId = jobId; |
| 28 | this.action = action; |
| 29 | Budget = budget; |
| 30 | this.output = output; |
| 31 | this.passwords = passwords; |
| 32 | this.reportState = reportState; |
| 33 | this.cancellation = cancellation; |
| 34 | this.maxPasswordAttempts = maxPasswordAttempts; |
| 35 | } |
| 36 | |
| 37 | public JobBudget Budget { get; } |
| 38 | public CancellationToken CancellationToken => cancellation.Token; |
| 39 | internal IReadOnlyList<EntryResult> Results => results.AsReadOnly(); |
| 40 | internal bool HasOutput => paths.Count != 0; |
| 41 | internal ArchiveError Failure => failure; |
| 42 | |
| 43 | public async ValueTask ListEntryAsync(ArchiveEntry entry) |
| 44 | { |
| 45 | await serial.WaitAsync(CancellationToken).ConfigureAwait(false); |
| 46 | try |
| 47 | { |
| 48 | Register(entry); |
| 49 | results.Add(new(entry, EntryOutcome.Listed, VerificationState.NotChecked, ArchiveError.None)); |
| 50 | ReportRunning(); |
| 51 | } |
| 52 | catch (ArchiveException error) |
| 53 | { |
| 54 | failure = error.Code; |
| 55 | throw; |
| 56 | } |
| 57 | finally { serial.Release(); } |
| 58 | } |
| 59 | |
| 60 | // 해제된 바이트를 직접 복사하여 헤더 크기와 무관하게 예산을 적용함. |
| 61 | // 검증 콜백은 스트림 끝에서 CRC 또는 인증 결과를 반환해야 함. |
| 62 | public async Task WriteEntryAsync(ArchiveEntry entry, Stream decoded, |
| 63 | Func<CancellationToken, ValueTask<VerificationState>> verify) |
| 64 | { |
| 65 | ArgumentNullException.ThrowIfNull(decoded); |
| 66 | ArgumentNullException.ThrowIfNull(verify); |
| 67 | await serial.WaitAsync(CancellationToken).ConfigureAwait(false); |
| 68 | try |
| 69 | { |
| 70 | if (action is not (ArchiveAction.Extract or ArchiveAction.Create or ArchiveAction.Recover)) |
| 71 | { |
| 72 | throw new ArchiveException(ArchiveError.UnsupportedOperation); |
| 73 | } |
| 74 | |
| 75 | Register(entry); |
| 76 | if (entry.Kind != EntryKind.File) |
| 77 | { |
| 78 | throw new ArchiveException(ArchiveError.UnsupportedEntry); |
| 79 | } |
| 80 | |
| 81 | var segments = OutputPathPolicy.Validate(entry.Name, OutputPathPolicy.CurrentPolicy); |
| 82 | var key = string.Join('/', segments); |
| 83 | if (paths.Any(existing => existing.Equals(key, OutputPathPolicy.Comparison(OutputPathPolicy.CurrentPolicy)) || |
| 84 | existing.StartsWith(key + "/", OutputPathPolicy.Comparison(OutputPathPolicy.CurrentPolicy)) || |
| 85 | key.StartsWith(existing + "/", OutputPathPolicy.Comparison(OutputPathPolicy.CurrentPolicy)))) |
| 86 | { |
| 87 | throw new ArchiveException(ArchiveError.OutputConflict); |
| 88 | } |
| 89 | |
| 90 | paths.Add(key); |
| 91 | await using (var destination = await output.CreateFileAsync(segments, CancellationToken).ConfigureAwait(false)) |
| 92 | { |
| 93 | var buffer = new byte[65536]; |
| 94 | try |
| 95 | { |
| 96 | while (true) |
| 97 | { |
| 98 | Budget.Check(CancellationToken); |
| 99 | var count = await decoded.ReadAsync(buffer.AsMemory(), CancellationToken).ConfigureAwait(false); |
| 100 | if (count == 0) { break; } |
| 101 | Budget.ChargeProcessed(count, CancellationToken); |
| 102 | Budget.ReserveOutput(count, CancellationToken); |
| 103 | await destination.WriteAsync(buffer.AsMemory(0, count), CancellationToken).ConfigureAwait(false); |
| 104 | ReportRunning(); |
| 105 | } |
| 106 | await destination.FlushAsync(CancellationToken).ConfigureAwait(false); |
| 107 | } |
| 108 | finally { System.Security.Cryptography.CryptographicOperations.ZeroMemory(buffer); } |
| 109 | } |
| 110 | |
| 111 | var verification = await verify(CancellationToken).ConfigureAwait(false); |
| 112 | Budget.Check(CancellationToken); |
| 113 | if (verification == VerificationState.Failed) |
| 114 | { |
| 115 | results.Add(new(entry, EntryOutcome.Failed, verification, ArchiveError.IntegrityFailure)); |
| 116 | throw new ArchiveException(ArchiveError.IntegrityFailure); |
| 117 | } |
| 118 | |
| 119 | results.Add(new(entry, EntryOutcome.Staged, verification, ArchiveError.None)); |
| 120 | } |
| 121 | catch (ArchiveException error) |
| 122 | { |
| 123 | failure = error.Code; |
| 124 | if (entryIds.Contains(entry.Id) && results.All(result => result.EntryId != entry.Id)) |
| 125 | { |
| 126 | results.Add(new(entry, EntryOutcome.Failed, VerificationState.NotChecked, error.Code)); |
| 127 | } |
| 128 | throw; |
| 129 | } |
| 130 | catch (Exception error) |
| 131 | { |
| 132 | failure = error is OperationCanceledException && CancellationToken.IsCancellationRequested |
| 133 | ? ArchiveError.Cancelled : ArchiveError.EngineFailure; |
| 134 | if (entry is not null && entryIds.Contains(entry.Id) && results.All(result => result.EntryId != entry.Id)) |
| 135 | { |
| 136 | results.Add(new(entry, EntryOutcome.Failed, VerificationState.NotChecked, failure)); |
| 137 | } |
| 138 | throw; |
| 139 | } |
| 140 | finally { serial.Release(); } |
| 141 | } |
| 142 | |
| 143 | // 제공자 호출을 직렬화함. 소비자는 잠금 밖에서 암호를 사용하고 재요청할 수 있음. |
| 144 | public async ValueTask<T> UsePasswordAsync<T>(Func<SecureString, CancellationToken, ValueTask<T>> consume) |
| 145 | { |
| 146 | ArgumentNullException.ThrowIfNull(consume); |
| 147 | await passwordSerial.WaitAsync(CancellationToken).ConfigureAwait(false); |
| 148 | SecureString? password = null; |
| 149 | var waiting = false; |
| 150 | try |
| 151 | { |
| 152 | try |
| 153 | { |
| 154 | Budget.Check(CancellationToken); |
| 155 | if (passwordAttempts >= maxPasswordAttempts) |
| 156 | { |
| 157 | failure = ArchiveError.PasswordAttemptsExceeded; |
| 158 | throw new ArchiveException(ArchiveError.PasswordAttemptsExceeded); |
| 159 | } |
| 160 | |
| 161 | var attempt = ++passwordAttempts; |
| 162 | waiting = true; |
| 163 | SetPasswordWaiting(true); |
| 164 | password = await passwords(new(jobId, Guid.NewGuid(), attempt), CancellationToken).ConfigureAwait(false); |
| 165 | if (password is null) |
| 166 | { |
| 167 | cancellation.Cancel(); |
| 168 | throw new OperationCanceledException(CancellationToken); |
| 169 | } |
| 170 | Budget.Check(CancellationToken); |
| 171 | } |
| 172 | finally |
| 173 | { |
| 174 | if (waiting) { SetPasswordWaiting(false); } |
| 175 | passwordSerial.Release(); |
| 176 | } |
| 177 | |
| 178 | Budget.Check(CancellationToken); |
| 179 | return await consume(password, CancellationToken).ConfigureAwait(false); |
| 180 | } |
| 181 | finally { password?.Dispose(); } |
| 182 | } |
| 183 | |
| 184 | private void SetPasswordWaiting(bool waiting) |
| 185 | { |
| 186 | lock (passwordStateGate) |
| 187 | { |
| 188 | waitingForPassword = waiting; |
| 189 | reportState(CancellationToken.IsCancellationRequested ? JobState.Cancelling : |
| 190 | waiting ? JobState.WaitingForPassword : JobState.Running); |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | private void ReportRunning() |
| 195 | { |
| 196 | lock (passwordStateGate) |
| 197 | { |
| 198 | // 다른 항목의 진행 보고가 활성 암호 요청 상태를 덮지 않도록 함. |
| 199 | if (!waitingForPassword) |
| 200 | { |
| 201 | reportState(CancellationToken.IsCancellationRequested ? JobState.Cancelling : JobState.Running); |
| 202 | } |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | private void Register(ArchiveEntry entry) |
| 207 | { |
| 208 | ArgumentNullException.ThrowIfNull(entry); |
| 209 | Budget.AddEntry(CancellationToken); |
| 210 | if (string.IsNullOrWhiteSpace(entry.Id) || !entryIds.Add(entry.Id) || entry.DeclaredSize < 0) |
| 211 | { |
| 212 | throw new ArchiveException(ArchiveError.UnsupportedEntry); |
| 213 | } |
| 214 | } |
| 215 | } |