team-ljyzipelo

공개

Merge pull request #103 from Team-LJY/fix/remove-csharp

C# 소스와 C# 전용 시험, .NET 설정 제거
작성자
LeeJunyoung
작성 시각
커밋
f1d9fa527ee335828376457284f890fde34fdb40
이 시점의 파일 보기

변경된 파일 107개

+0-2,695

변경 내용이 커서 일부 파일의 Diff를 생략했어요. 생략한 파일은 파일 보기나 Raw로 확인할 수 있어요.

수정.gitignore+0-9
@@ -2,8 +2,6 @@
22.messenger-*
33
44# Build, publish, and package output
5삭제: [Bb]in/
6삭제: [Oo]bj/
75artifacts/
86dist/
97publish/
@@ -11,7 +9,6 @@ packaging/output/
119packaging/staging/
1210
1311# Test and Python scratch data
14삭제: tests/security/.work/
1512# 로컬 시험, 리뷰, 설치 파일 작업 폴더
1613tests/work/
1714__pycache__/
@@ -19,14 +16,10 @@ __pycache__/
1916.pytest_cache/
2017.coverage
2118htmlcov/
22삭제: TestResults/
2319*.log
2420
2521# Local IDE and operating-system files
26삭제: .vs/
2722.idea/
28삭제: *.user
29삭제: *.suo
3023.DS_Store
3124Thumbs.db
3225
@@ -37,8 +30,6 @@ Thumbs.db
3730*.key
3831*.pfx
3932*.p12
40삭제: *.snk
41삭제: *.pubxml.user
4233
4334# Curated tests/**/fixtures/*.zip are intentional source fixtures.
4435# Do not add a blanket *.zip ignore rule.
삭제src/Zipelo.Core/ArchiveContracts.cs+0-83
@@ -1,83 +0,0 @@
1삭제: using System.Security;
2삭제:
3삭제: namespace Zipelo.Core;
4삭제:
5삭제: public enum ArchiveAction { List, Extract, Create, Verify, Preview, Recover }
6삭제: public enum JobState { Created, Running, WaitingForPassword, Cancelling, Completed, Partial, Cancelled, Failed }
7삭제: public enum EntryKind { File, Directory, SymbolicLink, HardLink, Other }
8삭제: public enum EntryOutcome { Listed, Staged, Extracted, Skipped, Failed }
9삭제: public enum VerificationState { NotChecked, Passed, Failed, Unavailable }
10삭제: public enum ArchiveError
11삭제: {
12삭제: None,
13삭제: EngineUnavailable,
14삭제: UnsupportedOperation,
15삭제: UnsafePath,
16삭제: UnsupportedEntry,
17삭제: OutputUnavailable,
18삭제: OutputConflict,
19삭제: BudgetExceeded,
20삭제: PasswordAttemptsExceeded,
21삭제: InvalidPasswordResponse,
22삭제: IntegrityFailure,
23삭제: Cancelled,
24삭제: EngineFailure
25삭제: }
26삭제:
27삭제: public sealed class ArchiveException(ArchiveError code) : Exception(code.ToString())
28삭제: {
29삭제: public ArchiveError Code { get; } = code;
30삭제: }
31삭제:
32삭제: public sealed record EngineCapability(string Format, ArchiveAction Action);
33삭제: public sealed record ArchiveEntry(string Id, string Name, EntryKind Kind, long? DeclaredSize);
34삭제: public sealed record EntryResult(ArchiveEntry Entry, EntryOutcome Outcome, VerificationState Verification, ArchiveError Error)
35삭제: {
36삭제: public string EntryId => Entry.Id;
37삭제: }
38삭제: public sealed record JobEvent(Guid JobId, long Sequence, JobState State, long ProcessedBytes);
39삭제: public sealed record PasswordChallenge(Guid JobId, Guid RequestId, int Attempt);
40삭제: public sealed record JobResult(Guid JobId, JobState State, IReadOnlyList<EntryResult> Entries, ArchiveError Error);
41삭제:
42삭제: // 호출자는 반환된 암호의 소유권을 코어에 넘김. 코어가 소비 종료 시 폐기함.
43삭제: // 제공자는 작업별로 한 번에 하나만 호출됨. 같은 작업의 암호 제공자를 재진입하지 않음.
44삭제: public delegate ValueTask<SecureString?> PasswordProvider(PasswordChallenge challenge, CancellationToken cancellationToken);
45삭제:
46삭제: public interface IArchiveEngine
47삭제: {
48삭제: IReadOnlyCollection<EngineCapability> Capabilities { get; }
49삭제:
50삭제: // 원본 경로나 출력 경로를 받지 않고 제한된 스트림과 작업 문맥만 사용함.
51삭제: // 시작한 문맥 작업을 모두 await하고 실패를 숨기지 않아야 함. 입력 스트림은 폐기하지 않음.
52삭제: Task ExecuteAsync(ArchiveAction action, IReadOnlyList<Stream> inputs, EngineContext context, CancellationToken cancellationToken);
53삭제: }
54삭제:
55삭제: public sealed class UnavailableEngine : IArchiveEngine
56삭제: {
57삭제: public IReadOnlyCollection<EngineCapability> Capabilities => Array.Empty<EngineCapability>();
58삭제:
59삭제: public Task ExecuteAsync(ArchiveAction action, IReadOnlyList<Stream> inputs, EngineContext context, CancellationToken cancellationToken)
60삭제: => Task.FromException(new ArchiveException(ArchiveError.EngineUnavailable));
61삭제: }
62삭제:
63삭제: // 저장 계층은 링크와 junction, 경로 교체 경쟁, 기존 파일 충돌을 실제 핸들 기준으로 차단해야 함.
64삭제: // 원본과 기존 파일은 수정하지 않으며 작업 소유 임시 출력만 폐기해야 함.
65삭제: // CommitAsync는 전체 게시 성공에만 정상 반환함. 실패나 취소 시 이미 게시한 작업 소유 출력도 원복해야 함.
66삭제: // 게시 성공 뒤에는 늦은 취소로 예외를 던지지 않음. 부분 게시만 가능한 저장 계층은 이 계약에 연결하지 않음.
67삭제: // DisposeAsync는 성공한 게시를 유지하고 미확정 출력을 정리함. 원복이나 정리 실패를 숨기지 않음.
68삭제: public interface IOutputTransaction : IAsyncDisposable
69삭제: {
70삭제: ValueTask<Stream> CreateFileAsync(IReadOnlyList<string> relativeSegments, CancellationToken cancellationToken);
71삭제: ValueTask CommitAsync(CancellationToken cancellationToken);
72삭제: }
73삭제:
74삭제: public sealed class UnavailableOutput : IOutputTransaction
75삭제: {
76삭제: public ValueTask<Stream> CreateFileAsync(IReadOnlyList<string> relativeSegments, CancellationToken cancellationToken)
77삭제: => ValueTask.FromException<Stream>(new ArchiveException(ArchiveError.OutputUnavailable));
78삭제:
79삭제: public ValueTask CommitAsync(CancellationToken cancellationToken)
80삭제: => ValueTask.FromException(new ArchiveException(ArchiveError.OutputUnavailable));
81삭제:
82삭제: public ValueTask DisposeAsync() => ValueTask.CompletedTask;
83삭제: }
삭제src/Zipelo.Core/ArchiveJob.cs+0-125
@@ -1,125 +0,0 @@
1삭제: namespace Zipelo.Core;
2삭제:
3삭제: public sealed class ArchiveJob
4삭제: {
5삭제: private readonly Guid id;
6삭제: private readonly JobLimits limits;
7삭제: private int started;
8삭제:
9삭제: public ArchiveJob(Guid id, JobLimits limits)
10삭제: {
11삭제: if (id == Guid.Empty) { throw new ArgumentException("작업 ID가 필요함", nameof(id)); }
12삭제: this.id = id;
13삭제: this.limits = limits;
14삭제: }
15삭제:
16삭제: // 입력 수명은 호출자가 소유함. 출력 트랜잭션은 작업이 소유하여 종료 전에 정리함.
17삭제: public async Task<JobResult> ExecuteAsync(ArchiveAction action, string format, IArchiveEngine engine,
18삭제: IReadOnlyList<Stream> readOnlyInputs, IOutputTransaction output, PasswordProvider passwords,
19삭제: IProgress<JobEvent>? progress, CancellationToken cancellationToken)
20삭제: {
21삭제: ArgumentNullException.ThrowIfNull(engine);
22삭제: ArgumentNullException.ThrowIfNull(readOnlyInputs);
23삭제: ArgumentNullException.ThrowIfNull(output);
24삭제: ArgumentNullException.ThrowIfNull(passwords);
25삭제: if (Interlocked.Exchange(ref started, 1) != 0)
26삭제: {
27삭제: throw new InvalidOperationException("작업 인스턴스는 재사용할 수 없음");
28삭제: }
29삭제:
30삭제: JobBudget? budget = null;
31삭제: EngineContext? context = null;
32삭제: CancellationTokenSource? linked = null;
33삭제: CancellationTokenRegistration cancellationRegistration = default;
34삭제: var eventGate = new object();
35삭제: long sequence = 0;
36삭제: void Report(JobState reportedState)
37삭제: {
38삭제: lock (eventGate)
39삭제: {
40삭제: if ((reportedState is JobState.Running or JobState.WaitingForPassword) &&
41삭제: (cancellationToken.IsCancellationRequested || linked?.IsCancellationRequested == true))
42삭제: {
43삭제: reportedState = JobState.Cancelling;
44삭제: }
45삭제:
46삭제: // 관찰자 오류가 정리나 실제 작업 결과를 바꾸지 않도록 함.
47삭제: try { progress?.Report(new(id, ++sequence, reportedState, budget?.Usage.ProcessedBytes ?? 0)); }
48삭제: catch { }
49삭제: }
50삭제: }
51삭제:
52삭제: var state = JobState.Failed;
53삭제: var error = ArchiveError.None;
54삭제: var committed = false;
55삭제: try
56삭제: {
57삭제: // 출력 소유권을 받은 뒤의 초기화도 정리 범위에 포함함.
58삭제: budget = new JobBudget(limits);
59삭제: linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
60삭제: cancellationRegistration = linked.Token.Register(() => Report(JobState.Cancelling));
61삭제: var inputs = readOnlyInputs.ToArray();
62삭제: context = new EngineContext(id, action, budget, output, passwords, Report, linked, limits.MaxPasswordAttempts);
63삭제: budget.Check(linked.Token);
64삭제: if (inputs.Length == 0 || inputs.Any(input => input is null || !input.CanRead || input.CanWrite))
65삭제: {
66삭제: throw new ArchiveException(ArchiveError.UnsupportedOperation);
67삭제: }
68삭제: if (!engine.Capabilities.Any(capability => capability.Action == action &&
69삭제: string.Equals(capability.Format, format, StringComparison.OrdinalIgnoreCase)))
70삭제: {
71삭제: throw new ArchiveException(engine is UnavailableEngine ? ArchiveError.EngineUnavailable : ArchiveError.UnsupportedOperation);
72삭제: }
73삭제:
74삭제: Report(JobState.Running);
75삭제: await engine.ExecuteAsync(action, Array.AsReadOnly(inputs), context, linked.Token).ConfigureAwait(false);
76삭제: budget.Check(linked.Token);
77삭제: if (context.Failure != ArchiveError.None)
78삭제: {
79삭제: throw new ArchiveException(context.Failure);
80삭제: }
81삭제: if (context.Results.Any(result => result.Error != ArchiveError.None || result.Verification == VerificationState.Failed))
82삭제: {
83삭제: throw new ArchiveException(ArchiveError.IntegrityFailure);
84삭제: }
85삭제:
86삭제: if (context.HasOutput)
87삭제: {
88삭제: await output.CommitAsync(linked.Token).ConfigureAwait(false);
89삭제: committed = true;
90삭제: }
91삭제: // 게시 성공 뒤의 늦은 취소로 실제 출력을 취소 결과로 바꾸지 않음.
92삭제: state = JobState.Completed;
93삭제: }
94삭제: catch (OperationCanceledException) when (linked?.IsCancellationRequested == true || cancellationToken.IsCancellationRequested)
95삭제: {
96삭제: state = JobState.Cancelled;
97삭제: error = ArchiveError.Cancelled;
98삭제: }
99삭제: catch (ArgumentException) when (context is null) { error = ArchiveError.UnsupportedOperation; }
100삭제: catch (ArchiveException failure) { error = failure.Code; }
101삭제: catch { error = ArchiveError.EngineFailure; }
102삭제: finally
103삭제: {
104삭제: try { await output.DisposeAsync().ConfigureAwait(false); }
105삭제: catch
106삭제: {
107삭제: state = JobState.Failed;
108삭제: if (error == ArchiveError.None) { error = ArchiveError.OutputUnavailable; }
109삭제: }
110삭제: finally
111삭제: {
112삭제: // 종료 이벤트 뒤에 취소 이벤트가 나오지 않도록 등록을 먼저 해제함.
113삭제: cancellationRegistration.Dispose();
114삭제: linked?.Dispose();
115삭제: }
116삭제: }
117삭제:
118삭제: var results = (context?.Results ?? Array.Empty<EntryResult>()).Select(result => result.Outcome == EntryOutcome.Staged
119삭제: ? result with { Outcome = committed ? EntryOutcome.Extracted : EntryOutcome.Failed,
120삭제: Error = committed ? ArchiveError.None : error }
121삭제: : result).ToArray();
122삭제: Report(state);
123삭제: return new(id, state, Array.AsReadOnly(results), error);
124삭제: }
125삭제: }
삭제src/Zipelo.Core/EngineContext.cs+0-215
@@ -1,215 +0,0 @@
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삭제: }
삭제src/Zipelo.Core/JobBudget.cs+0-75
@@ -1,75 +0,0 @@
1삭제: namespace Zipelo.Core;
2삭제:
3삭제: // 제한값은 호스트가 정함. 아래 값은 제품 기본값이나 성능 약속이 아님.
4삭제: public sealed record JobLimits(long MaxEntries, long MaxProcessedBytes, long MaxOutputBytes, TimeSpan MaxDuration, int MaxPasswordAttempts);
5삭제: public sealed record BudgetUsage(long Entries, long ProcessedBytes, long OutputBytes);
6삭제:
7삭제: public sealed class JobBudget
8삭제: {
9삭제: private readonly object gate = new();
10삭제: private readonly JobLimits limits;
11삭제: private readonly TimeProvider time;
12삭제: private readonly long started;
13삭제: private long entries;
14삭제: private long processedBytes;
15삭제: private long outputBytes;
16삭제: private int exhausted;
17삭제:
18삭제: public JobBudget(JobLimits limits, TimeProvider? timeProvider = null)
19삭제: {
20삭제: ArgumentNullException.ThrowIfNull(limits);
21삭제: if (limits.MaxEntries <= 0 || limits.MaxProcessedBytes <= 0 || limits.MaxOutputBytes <= 0 ||
22삭제: limits.MaxDuration <= TimeSpan.Zero || limits.MaxPasswordAttempts <= 0)
23삭제: {
24삭제: throw new ArgumentOutOfRangeException(nameof(limits));
25삭제: }
26삭제:
27삭제: this.limits = limits;
28삭제: time = timeProvider ?? TimeProvider.System;
29삭제: started = time.GetTimestamp();
30삭제: }
31삭제:
32삭제: public BudgetUsage Usage
33삭제: {
34삭제: get { lock (gate) { return new(entries, processedBytes, outputBytes); } }
35삭제: }
36삭제:
37삭제: public void Check(CancellationToken cancellationToken)
38삭제: {
39삭제: cancellationToken.ThrowIfCancellationRequested();
40삭제: if (Volatile.Read(ref exhausted) != 0 || time.GetElapsedTime(started) >= limits.MaxDuration)
41삭제: {
42삭제: Interlocked.Exchange(ref exhausted, 1);
43삭제: throw new ArchiveException(ArchiveError.BudgetExceeded);
44삭제: }
45삭제: }
46삭제:
47삭제: public void AddEntry(CancellationToken cancellationToken) => Charge(1, 0, 0, cancellationToken);
48삭제:
49삭제: // 중간 TAR, 솔리드 선행 처리, 복구 재시도도 같은 인스턴스에 누적함.
50삭제: public void ChargeProcessed(long bytes, CancellationToken cancellationToken) => Charge(0, bytes, 0, cancellationToken);
51삭제: public void ReserveOutput(long bytes, CancellationToken cancellationToken) => Charge(0, 0, bytes, cancellationToken);
52삭제:
53삭제: private void Charge(long entryCount, long processed, long output, CancellationToken cancellationToken)
54삭제: {
55삭제: if (entryCount < 0 || processed < 0 || output < 0)
56삭제: {
57삭제: throw new ArgumentOutOfRangeException(nameof(processed));
58삭제: }
59삭제:
60삭제: lock (gate)
61삭제: {
62삭제: Check(cancellationToken);
63삭제: if (entryCount > limits.MaxEntries - entries || processed > limits.MaxProcessedBytes - processedBytes ||
64삭제: output > limits.MaxOutputBytes - outputBytes)
65삭제: {
66삭제: Interlocked.Exchange(ref exhausted, 1);
67삭제: throw new ArchiveException(ArchiveError.BudgetExceeded);
68삭제: }
69삭제:
70삭제: entries += entryCount;
71삭제: processedBytes += processed;
72삭제: outputBytes += output;
73삭제: }
74삭제: }
75삭제: }
삭제src/Zipelo.Core/OutputPathPolicy.cs+0-82
@@ -1,82 +0,0 @@
1삭제: using System.Text;
2삭제:
3삭제: namespace Zipelo.Core;
4삭제:
5삭제: public enum FileNamePolicy { Windows, Linux }
6삭제:
7삭제: public static class OutputPathPolicy
8삭제: {
9삭제: public static FileNamePolicy CurrentPolicy => OperatingSystem.IsWindows() ? FileNamePolicy.Windows :
10삭제: OperatingSystem.IsLinux() ? FileNamePolicy.Linux : throw new PlatformNotSupportedException();
11삭제:
12삭제: public static StringComparison Comparison(FileNamePolicy policy) => policy switch
13삭제: {
14삭제: FileNamePolicy.Windows => StringComparison.OrdinalIgnoreCase,
15삭제: FileNamePolicy.Linux => StringComparison.Ordinal,
16삭제: _ => throw new ArgumentOutOfRangeException(nameof(policy))
17삭제: };
18삭제:
19삭제: public static StringComparer Comparer(FileNamePolicy policy) => policy switch
20삭제: {
21삭제: FileNamePolicy.Windows => StringComparer.OrdinalIgnoreCase,
22삭제: FileNamePolicy.Linux => StringComparer.Ordinal,
23삭제: _ => throw new ArgumentOutOfRangeException(nameof(policy))
24삭제: };
25삭제:
26삭제: public static IReadOnlyList<string> Validate(string path, FileNamePolicy policy)
27삭제: {
28삭제: if (policy == FileNamePolicy.Windows) { return Validate(path); }
29삭제: if (policy != FileNamePolicy.Linux) { throw new ArgumentOutOfRangeException(nameof(policy)); }
30삭제: if (string.IsNullOrEmpty(path) || path.Length > 4096 || path.Contains('\0'))
31삭제: {
32삭제: throw new ArchiveException(ArchiveError.UnsafePath);
33삭제: }
34삭제: var segments = path.Split('/');
35삭제: var encoding = new UTF8Encoding(false, true);
36삭제: foreach (var segment in segments)
37삭제: {
38삭제: if (segment.Length == 0 || segment is "." or "..")
39삭제: {
40삭제: throw new ArchiveException(ArchiveError.UnsafePath);
41삭제: }
42삭제: try
43삭제: {
44삭제: if (encoding.GetByteCount(segment) > 255) { throw new ArchiveException(ArchiveError.UnsafePath); }
45삭제: }
46삭제: catch (EncoderFallbackException) { throw new ArchiveException(ArchiveError.UnsafePath); }
47삭제: }
48삭제: return Array.AsReadOnly(segments);
49삭제: }
50삭제:
51삭제: // 기존 단일 인수 API는 Windows 사전 정책을 유지함.
52삭제: // 문자열 검사는 사전 정책임. 파일시스템의 링크나 경쟁 상태를 검사한 결과가 아님.
53삭제: public static IReadOnlyList<string> Validate(string path)
54삭제: {
55삭제: if (string.IsNullOrWhiteSpace(path) || path.Length > 4096)
56삭제: {
57삭제: throw new ArchiveException(ArchiveError.UnsafePath);
58삭제: }
59삭제:
60삭제: var segments = path.Replace('\\', '/').Split('/');
61삭제: foreach (var segment in segments)
62삭제: {
63삭제: if (segment.Length is 0 or > 255 || segment is "." or ".." ||
64삭제: segment.EndsWith(' ') || segment.EndsWith('.') ||
65삭제: !segment.IsNormalized(NormalizationForm.FormC) ||
66삭제: segment.Any(c => char.IsControl(c) || "<>:\"|?*".Contains(c)))
67삭제: {
68삭제: throw new ArchiveException(ArchiveError.UnsafePath);
69삭제: }
70삭제:
71삭제: var stem = segment.Split('.')[0].TrimEnd(' ').ToUpperInvariant();
72삭제: if (stem is "CON" or "PRN" or "AUX" or "NUL" or "CONIN$" or "CONOUT$" ||
73삭제: (stem.Length == 4 && (stem.StartsWith("COM") || stem.StartsWith("LPT")) &&
74삭제: "123456789¹²³".Contains(stem[3])))
75삭제: {
76삭제: throw new ArchiveException(ArchiveError.UnsafePath);
77삭제: }
78삭제: }
79삭제:
80삭제: return Array.AsReadOnly(segments);
81삭제: }
82삭제: }
삭제src/Zipelo.Core/Zipelo.Core.csproj+0-8
@@ -1,8 +0,0 @@
1삭제: <Project Sdk="Microsoft.NET.Sdk">
2삭제: <PropertyGroup>
3삭제: <TargetFramework>net10.0</TargetFramework>
4삭제: <Nullable>enable</Nullable>
5삭제: <ImplicitUsings>enable</ImplicitUsings>
6삭제: <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
7삭제: </PropertyGroup>
8삭제: </Project>
삭제src/Zipelo.Desktop/App.xaml+0-21
@@ -1,21 +0,0 @@
1삭제: <Application x:Class="Zipelo.Desktop.App"
2삭제: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3삭제: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
4삭제: <Application.Resources>
5삭제: <Style TargetType="Window">
6삭제: <Setter Property="FontFamily" Value="Malgun Gothic" />
7삭제: <Setter Property="FontSize" Value="16" />
8삭제: <Setter Property="Foreground" Value="#17263C" />
9삭제: <Setter Property="Background" Value="#F3F6FA" />
10삭제: </Style>
11삭제: <Style TargetType="Button">
12삭제: <Setter Property="Padding" Value="20,12" />
13삭제: <Setter Property="Margin" Value="0,0,12,0" />
14삭제: <Setter Property="MinHeight" Value="48" />
15삭제: <Setter Property="MinWidth" Value="100" />
16삭제: </Style>
17삭제: <Style TargetType="TextBlock">
18삭제: <Setter Property="TextWrapping" Value="Wrap" />
19삭제: </Style>
20삭제: </Application.Resources>
21삭제: </Application>
삭제src/Zipelo.Desktop/App.xaml.cs+0-18
@@ -1,18 +0,0 @@
1삭제: using System.Windows;
2삭제:
3삭제: namespace Zipelo.Desktop;
4삭제:
5삭제: public partial class App : Application
6삭제: {
7삭제: protected override void OnStartup(StartupEventArgs e)
8삭제: {
9삭제: base.OnStartup(e);
10삭제: var fallback = new UnavailableWorkspace();
11삭제: var workspace = ZipWorkerWorkspace.TryCreate(out var unavailableReason);
12삭제: fallback.AvailabilityMessage = unavailableReason;
13삭제: var window = new MainWindow(workspace ?? fallback);
14삭제: MainWindow = window;
15삭제: window.ContentRendered += async (_, _) => await window.OpenStartupAsync(e.Args);
16삭제: window.Show();
17삭제: }
18삭제: }
삭제src/Zipelo.Desktop/ArchiveOpenArguments.cs+0-55
@@ -1,55 +0,0 @@
1삭제: using System.IO;
2삭제:
3삭제: namespace Zipelo.Ui;
4삭제:
5삭제: public sealed record ArchiveOpenTarget(string? Path, string? Error);
6삭제:
7삭제: public static class ArchiveOpenArguments
8삭제: {
9삭제: public static ArchiveOpenTarget Parse(IReadOnlyList<string> arguments)
10삭제: {
11삭제: if (arguments.Count == 0) { return new(null, null); }
12삭제: if (arguments.Count != 1)
13삭제: {
14삭제: return new(null, "압축파일은 한 번에 하나만 열 수 있습니다. 단일 로컬 ZIP 경로를 전달하세요.");
15삭제: }
16삭제: var path = arguments[0];
17삭제: if (path.StartsWith('-') || (OperatingSystem.IsWindows() && path.StartsWith('/')))
18삭제: {
19삭제: return new(null, "알 수 없는 옵션입니다. 옵션 없이 단일 로컬 ZIP 절대 경로를 전달하세요.");
20삭제: }
21삭제: return ValidatePath(path);
22삭제: }
23삭제:
24삭제: public static string? ValidateName(string name) => Path.GetExtension(name).ToLowerInvariant() switch
25삭제: {
26삭제: ".jar" => "JAR 파일은 지원 대상에서 제외됩니다.",
27삭제: ".zip" => null,
28삭제: _ => "현재는 .zip 파일의 목록 열기만 지원합니다. 다른 형식은 열 수 없습니다."
29삭제: };
30삭제:
31삭제: public static ArchiveOpenTarget ValidatePath(string path)
32삭제: {
33삭제: try
34삭제: {
35삭제: // URI, UNC 및 장치 경로를 실행 인수나 원격 주소로 재해석하지 않음.
36삭제: if (string.IsNullOrWhiteSpace(path) || path.Contains('\0') ||
37삭제: !Path.IsPathFullyQualified(path) || path.StartsWith(@"\\") || path.StartsWith("//"))
38삭제: {
39삭제: return new(null, "로컬 파일의 절대 경로가 필요합니다. URI, 네트워크와 장치 경로는 지원하지 않습니다.");
40삭제: }
41삭제: var error = ValidateName(path);
42삭제: if (error is not null) { return new(null, error); }
43삭제: if (!File.Exists(path)) { return new(null, "파일이 없거나 읽을 수 없습니다. 파일 위치와 접근 권한을 확인하세요."); }
44삭제: if ((File.GetAttributes(path) & (FileAttributes.Directory | FileAttributes.Device)) != 0)
45삭제: {
46삭제: return new(null, "폴더나 장치는 열 수 없습니다. 일반 ZIP 파일을 선택하세요.");
47삭제: }
48삭제: return new(Path.GetFullPath(path), null);
49삭제: }
50삭제: catch (Exception error) when (error is ArgumentException or IOException or UnauthorizedAccessException or NotSupportedException)
51삭제: {
52삭제: return new(null, "파일 경로를 확인하지 못했습니다. 올바른 로컬 ZIP 경로를 전달하세요.");
53삭제: }
54삭제: }
55삭제: }
삭제src/Zipelo.Desktop/CoreWorkspace.cs+0-163
@@ -1,163 +0,0 @@
1삭제: using System.Security;
2삭제: using Zipelo.Core;
3삭제:
4삭제: namespace Zipelo.Desktop;
5삭제:
6삭제: // 호스트는 별도 작업 프로세스를 사용하고 입력과 출력 정리를 마친 뒤 반환해야 함.
7삭제: public delegate Task<JobResult> CoreJobRunner(
8삭제: WorkspaceRequest request,
9삭제: IProgress<JobEvent> progress,
10삭제: PasswordProvider passwords,
11삭제: CancellationToken cancellationToken);
12삭제:
13삭제: public sealed class CoreWorkspace : IArchiveWorkspace, IWorkspaceCapabilities
14삭제: {
15삭제: private readonly CoreJobRunner run;
16삭제: private readonly string? availabilityMessage;
17삭제: private readonly IReadOnlyList<EngineCapability> capabilities;
18삭제:
19삭제: public CoreWorkspace(CoreJobRunner run, IEnumerable<EngineCapability> capabilities, string? availabilityMessage = null)
20삭제: {
21삭제: ArgumentNullException.ThrowIfNull(run);
22삭제: ArgumentNullException.ThrowIfNull(capabilities);
23삭제: this.run = run;
24삭제: this.availabilityMessage = availabilityMessage;
25삭제: this.capabilities = Array.AsReadOnly(capabilities.ToArray());
26삭제: }
27삭제:
28삭제: public bool IsAvailable => capabilities.Any(capability =>
29삭제: capability.Action is ArchiveAction.List or ArchiveAction.Create);
30삭제:
31삭제: public string AvailabilityMessage => availabilityMessage ?? (IsAvailable
32삭제: ? "연결된 형식과 기능만 사용할 수 있습니다. 압축 풀기는 안전 검증 전까지 준비 중입니다."
33삭제: : "작업 프로세스가 아직 연결되지 않았습니다. 파일을 처리할 수 없습니다.");
34삭제:
35삭제: public bool CanExecute(WorkspaceAction action, string format)
36삭제: {
37삭제: // 안전한 출력 계층의 Windows 검증 전까지 해제를 닫아 둠.
38삭제: return action != WorkspaceAction.Extract && capabilities.Any(capability =>
39삭제: capability.Action == MapAction(action) &&
40삭제: string.Equals(capability.Format, format, StringComparison.OrdinalIgnoreCase));
41삭제: }
42삭제:
43삭제: public async Task<WorkspaceResult> ExecuteAsync(
44삭제: WorkspaceRequest request,
45삭제: IProgress<WorkspaceProgress> progress,
46삭제: Func<PasswordChallenge, CancellationToken, Task<SecureString?>> requestPassword,
47삭제: CancellationToken cancellationToken)
48삭제: {
49삭제: ArgumentNullException.ThrowIfNull(request);
50삭제: ArgumentNullException.ThrowIfNull(progress);
51삭제: ArgumentNullException.ThrowIfNull(requestPassword);
52삭제: if (request.JobId == Guid.Empty || request.Sources.Count == 0)
53삭제: {
54삭제: throw new ArchiveException(ArchiveError.UnsupportedOperation);
55삭제: }
56삭제: if (!CanExecute(request.Action, request.Format))
57삭제: {
58삭제: return new(WorkspaceOutcome.Failed, Array.Empty<FileRow>())
59삭제: {
60삭제: JobId = request.JobId,
61삭제: Error = IsAvailable ? ArchiveError.UnsupportedOperation : ArchiveError.EngineUnavailable
62삭제: };
63삭제: }
64삭제:
65삭제: var gate = new object();
66삭제: long lastSequence = 0;
67삭제: var finished = false;
68삭제: var events = new ForwardProgress<JobEvent>(value =>
69삭제: {
70삭제: lock (gate)
71삭제: {
72삭제: if (finished || value.JobId != request.JobId || value.Sequence <= lastSequence)
73삭제: {
74삭제: return;
75삭제: }
76삭제: lastSequence = value.Sequence;
77삭제: progress.Report(new(value.ProcessedBytes, null)
78삭제: {
79삭제: JobId = value.JobId,
80삭제: Sequence = value.Sequence,
81삭제: State = value.State
82삭제: });
83삭제: }
84삭제: });
85삭제:
86삭제: async ValueTask<SecureString?> Passwords(Zipelo.Core.PasswordChallenge challenge, CancellationToken token)
87삭제: {
88삭제: if (challenge.JobId != request.JobId || challenge.RequestId == Guid.Empty)
89삭제: {
90삭제: throw new ArchiveException(ArchiveError.InvalidPasswordResponse);
91삭제: }
92삭제: // 성공한 전달 이후 암호는 Core가 소비와 폐기를 소유함.
93삭제: return await requestPassword(new(challenge.JobId, challenge.RequestId)
94삭제: {
95삭제: Attempt = challenge.Attempt
96삭제: }, token).ConfigureAwait(false);
97삭제: }
98삭제:
99삭제: try
100삭제: {
101삭제: var result = await run(request, events, Passwords, cancellationToken).ConfigureAwait(false);
102삭제: if (result.JobId != request.JobId)
103삭제: {
104삭제: throw new ArchiveException(ArchiveError.EngineFailure);
105삭제: }
106삭제: return MapResult(result);
107삭제: }
108삭제: finally
109삭제: {
110삭제: lock (gate) { finished = true; }
111삭제: }
112삭제: }
113삭제:
114삭제: private static ArchiveAction MapAction(WorkspaceAction action) => action switch
115삭제: {
116삭제: WorkspaceAction.List => ArchiveAction.List,
117삭제: WorkspaceAction.Create => ArchiveAction.Create,
118삭제: WorkspaceAction.Extract => ArchiveAction.Extract,
119삭제: _ => throw new ArchiveException(ArchiveError.UnsupportedOperation)
120삭제: };
121삭제:
122삭제: internal static WorkspaceResult MapResult(JobResult result)
123삭제: {
124삭제: var terminal = result.State is JobState.Completed or JobState.Partial or JobState.Cancelled or JobState.Failed;
125삭제: var outcome = result.State switch
126삭제: {
127삭제: JobState.Completed => WorkspaceOutcome.Completed,
128삭제: JobState.Partial => WorkspaceOutcome.Partial,
129삭제: JobState.Cancelled => WorkspaceOutcome.Cancelled,
130삭제: _ => WorkspaceOutcome.Failed
131삭제: };
132삭제: var rows = result.Entries.Select(value => new FileRow(
133삭제: value.Entry.Name,
134삭제: value.Entry.DeclaredSize is long size ? $"{size:N0}바이트" : "알 수 없음",
135삭제: value.Verification switch
136삭제: {
137삭제: VerificationState.Passed => "검증 통과",
138삭제: VerificationState.Failed => "검증 실패",
139삭제: VerificationState.Unavailable => "검증 불가",
140삭제: _ => "검증 전"
141삭제: })
142삭제: {
143삭제: EntryId = value.Entry.Id,
144삭제: Kind = value.Entry.Kind,
145삭제: Outcome = value.Outcome,
146삭제: Error = value.Error
147삭제: }).ToArray();
148삭제: if (outcome == WorkspaceOutcome.Completed && result.Error != ArchiveError.None)
149삭제: {
150삭제: outcome = WorkspaceOutcome.Failed;
151삭제: }
152삭제: return new(outcome, Array.AsReadOnly(rows))
153삭제: {
154삭제: JobId = result.JobId,
155삭제: Error = terminal ? result.Error : ArchiveError.EngineFailure
156삭제: };
157삭제: }
158삭제:
159삭제: private sealed class ForwardProgress<T>(Action<T> report) : IProgress<T>
160삭제: {
161삭제: public void Report(T value) => report(value);
162삭제: }
163삭제: }
삭제src/Zipelo.Desktop/CreationWorkspace.cs+0-73
@@ -1,73 +0,0 @@
1삭제: using System.IO;
2삭제: using System.Security;
3삭제: using Zipelo.Core;
4삭제: using Zipelo.Runtime;
5삭제: using Zipelo.Ui;
6삭제:
7삭제: namespace Zipelo.Desktop;
8삭제:
9삭제: internal sealed class CreationWorkspace(CoreWorkspace listing, ZipWorkerClient client, Func<bool> filesReady)
10삭제: : IArchiveWorkspace, IWorkspaceCapabilities
11삭제: {
12삭제: public bool IsAvailable => listing.IsAvailable && filesReady();
13삭제: public string AvailabilityMessage => listing.AvailabilityMessage +
14삭제: (ZipExtractionWorkflow.ValidationEnabled ? " " + ZipExtractionWorkflow.ScopeMessage : " 일반 압축 풀기는 비활성입니다.") +
15삭제: (ZipCreationWorkflow.ValidationEnabled ? " " + ZipCreationWorkflow.ScopeMessage : " 생성 연결은 개발 검증 빌드에서만 사용할 수 있습니다.");
16삭제:
17삭제: public bool CanExecute(WorkspaceAction action, string format) => IsAvailable &&
18삭제: (action == WorkspaceAction.Create
19삭제: ? ZipCreationWorkflow.ValidationEnabled && NewZipPublisher.IsSupportedPlatform &&
20삭제: format.Equals("zip", StringComparison.OrdinalIgnoreCase)
21삭제: : action == WorkspaceAction.Extract
22삭제: ? ZipExtractionWorkflow.ValidationEnabled && NewFolderPublisher.IsSupportedPlatform &&
23삭제: client.SupportsMemoryExtraction && format.Equals("zip", StringComparison.OrdinalIgnoreCase)
24삭제: : listing.CanExecute(action, format));
25삭제:
26삭제: public async Task<WorkspaceResult> ExecuteAsync(WorkspaceRequest request, IProgress<WorkspaceProgress> progress,
27삭제: Func<PasswordChallenge, CancellationToken, Task<SecureString?>> requestPassword, CancellationToken token)
28삭제: {
29삭제: if (!CanExecute(request.Action, request.Format)) { throw new ArchiveException(ArchiveError.UnsupportedOperation); }
30삭제: if (request.Action == WorkspaceAction.Extract)
31삭제: {
32삭제: if (request.Sources.Count != 1 || request.Destination is null ||
33삭제: ArchiveOpenArguments.ValidatePath(request.Sources[0]).Error is not null)
34삭제: {
35삭제: throw new ArchiveException(ArchiveError.UnsupportedOperation);
36삭제: }
37삭제: var extraction = await ZipExtractionWorkflow.RunAsync(client, request.JobId, cancellation =>
38삭제: {
39삭제: cancellation.ThrowIfCancellationRequested();
40삭제: return Task.FromResult<Stream>(new FileStream(request.Sources[0], FileMode.Open,
41삭제: FileAccess.Read, FileShare.Read, 65536, FileOptions.Asynchronous | FileOptions.SequentialScan));
42삭제: }, request.Destination, token).ConfigureAwait(false);
43삭제: var extracted = CoreWorkspace.MapResult(extraction.Job);
44삭제: var extractionError = extraction.Publication?.Error ?? extraction.Job.Error;
45삭제: var extractionOutcome = ZipExtractionWorkflow.Published(extraction) ? WorkspaceOutcome.Completed
46삭제: : extractionError == ArchiveError.Cancelled ? WorkspaceOutcome.Cancelled : WorkspaceOutcome.Failed;
47삭제: return extracted with { Outcome = extractionOutcome, Error = extractionError, Extraction = extraction };
48삭제: }
49삭제: if (request.Action != WorkspaceAction.Create)
50삭제: {
51삭제: return await listing.ExecuteAsync(request, progress, requestPassword, token).ConfigureAwait(false);
52삭제: }
53삭제: if (request.Destination is null) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
54삭제: var sources = request.Sources.Select(path => new CreationSource(Path.GetFileName(path), cancellation =>
55삭제: {
56삭제: cancellation.ThrowIfCancellationRequested();
57삭제: // 디렉터리 재귀 수집 없이 사용자가 고른 파일만 읽음.
58삭제: if ((File.GetAttributes(path) & FileAttributes.Directory) != 0)
59삭제: {
60삭제: throw new ArchiveException(ArchiveError.UnsupportedEntry);
61삭제: }
62삭제: return Task.FromResult<Stream>(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
63삭제: 65536, FileOptions.Asynchronous | FileOptions.SequentialScan));
64삭제: })).ToArray();
65삭제: var result = await ZipCreationWorkflow.RunAsync(client, request.JobId, sources, request.Destination, token)
66삭제: .ConfigureAwait(false);
67삭제: var mapped = CoreWorkspace.MapResult(result.Job);
68삭제: var error = result.Publication?.Error ?? result.Job.Error;
69삭제: var outcome = result.Publication?.Published == true ? WorkspaceOutcome.Completed
70삭제: : error == ArchiveError.Cancelled ? WorkspaceOutcome.Cancelled : WorkspaceOutcome.Failed;
71삭제: return mapped with { Outcome = outcome, Error = error, Creation = result };
72삭제: }
73삭제: }
삭제src/Zipelo.Desktop/MainWindow.xaml+0-62
@@ -1,62 +0,0 @@
1삭제: <Window x:Class="Zipelo.Desktop.MainWindow"
2삭제: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3삭제: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4삭제: Title="Zipelo" Width="980" Height="740" MinWidth="640" MinHeight="520"
5삭제: Closing="OnClosing">
6삭제: <Grid Margin="28">
7삭제: <Grid.RowDefinitions>
8삭제: <RowDefinition Height="Auto" />
9삭제: <RowDefinition Height="Auto" />
10삭제: <RowDefinition Height="Auto" />
11삭제: <RowDefinition Height="*" />
12삭제: <RowDefinition Height="Auto" />
13삭제: </Grid.RowDefinitions>
14삭제: <DockPanel Margin="0,0,0,24">
15삭제: <Button DockPanel.Dock="Right" Content="설치 안내" Click="ShowInstallation" Margin="0" />
16삭제: <StackPanel>
17삭제: <TextBlock Text="Zipelo" FontSize="36" FontWeight="Bold" />
18삭제: <TextBlock Text="파일을 열고, 간편하게 풀어보세요." Margin="0,4,12,0" />
19삭제: </StackPanel>
20삭제: </DockPanel>
21삭제: <WrapPanel Grid.Row="1" Margin="0,0,0,20">
22삭제: <Button x:Name="OpenButton" Content="압축파일 열기" Click="OpenArchive"
23삭제: Background="#185ABD" Foreground="White" FontWeight="SemiBold" Margin="0,0,12,8" />
24삭제: <Button x:Name="CreateButton" Content="새로 압축하기" Click="CreateArchive" Margin="0,0,12,8" />
25삭제: <Button x:Name="RetryCreateButton" Content="생성 다시 시도" Click="RetryCreation" IsEnabled="False" Margin="0,0,12,8" />
26삭제: <Button x:Name="ExtractButton" Content="압축 풀기" Click="ExtractArchive" IsEnabled="False" Margin="0,0,12,8" />
27삭제: </WrapPanel>
28삭제: <StackPanel Grid.Row="2" Margin="0,0,0,16">
29삭제: <TextBlock x:Name="ArchiveTitle" Text="아직 열린 압축파일이 없습니다." FontSize="20" FontWeight="SemiBold" />
30삭제: <TextBlock x:Name="Availability" TextWrapping="Wrap" Text="개발 중인 화면입니다. 압축 엔진 연결 전에는 파일을 처리할 수 없습니다."
31삭제: Margin="0,8,0,0" />
32삭제: </StackPanel>
33삭제: <Grid Grid.Row="3" Background="White">
34삭제: <DataGrid x:Name="Files" AutoGenerateColumns="False" IsReadOnly="True"
35삭제: CanUserAddRows="False" CanUserDeleteRows="False" CanUserReorderColumns="False"
36삭제: HeadersVisibility="Column" GridLinesVisibility="Horizontal"
37삭제: RowHeaderWidth="0" BorderBrush="#CFD7E3" RowHeight="40"
38삭제: EnableRowVirtualization="True" EnableColumnVirtualization="True"
39삭제: AutomationProperties.Name="압축파일 안의 파일 목록">
40삭제: <DataGrid.Columns>
41삭제: <DataGridTextColumn Header="파일 이름" Binding="{Binding Name}" Width="*" MinWidth="200" />
42삭제: <DataGridTextColumn Header="크기" Binding="{Binding Size}" Width="120" />
43삭제: <DataGridTextColumn Header="검증 상태" Binding="{Binding Verification}" Width="150" />
44삭제: </DataGrid.Columns>
45삭제: </DataGrid>
46삭제: <TextBlock x:Name="EmptyState" Text="압축파일을 열면 여기에 파일 목록이 표시됩니다."
47삭제: HorizontalAlignment="Center" VerticalAlignment="Center" Margin="24"
48삭제: IsHitTestVisible="False" />
49삭제: </Grid>
50삭제: <StackPanel Grid.Row="4" Margin="0,20,0,0">
51삭제: <TextBlock x:Name="Status" Text="작업 대기 중" AutomationProperties.LiveSetting="Polite" />
52삭제: <TextBlock x:Name="CreationSelection" TextWrapping="Wrap" Margin="0,8,0,0" />
53삭제: <TextBlock Text="새 결과 폴더 이름 (기존 대상과 병합하지 않음)" Margin="0,8,0,0" />
54삭제: <TextBox x:Name="ExtractionName" Text="압축 푼 파일" AutomationProperties.Name="새 결과 폴더 이름" />
55삭제: <TextBlock x:Name="ExtractionSelection" TextWrapping="Wrap" />
56삭제: <TextBlock x:Name="ResultSummary" Margin="0,8,0,0" />
57삭제: <ProgressBar x:Name="Progress" Height="8" Margin="0,12,0,16" Minimum="0" Maximum="100"
58삭제: AutomationProperties.Name="작업 진행률" />
59삭제: <Button x:Name="StopButton" Content="작업 중지" Click="StopJob" IsEnabled="False" HorizontalAlignment="Left" />
60삭제: </StackPanel>
61삭제: </Grid>
62삭제: </Window>
삭제src/Zipelo.Desktop/MainWindow.xaml.cs+0-432
@@ -1,432 +0,0 @@
1삭제: using System.ComponentModel;
2삭제: using System.IO;
3삭제: using System.Security;
4삭제: using System.Windows;
5삭제: using System.Windows.Media;
6삭제: using Microsoft.Win32;
7삭제: using Zipelo.Core;
8삭제: using Zipelo.Ui;
9삭제:
10삭제: namespace Zipelo.Desktop;
11삭제:
12삭제: public partial class MainWindow : Window
13삭제: {
14삭제: private enum ScreenPhase { Idle, Selecting, Running, WaitingForPassword, Cancelling, Finishing }
15삭제:
16삭제: private readonly IArchiveWorkspace workspace;
17삭제: private readonly HashSet<Guid> passwordRequests = [];
18삭제: private ScreenPhase phase;
19삭제: private CancellationTokenSource? activeJob;
20삭제: private Guid? activeJobId;
21삭제: private long lastSequence;
22삭제: private string? archivePath;
23삭제: private PasswordWindow? passwordWindow;
24삭제: private string[] creationSources = [];
25삭제: private string? creationDestination;
26삭제: private bool startupHandled;
27삭제:
28삭제: public MainWindow(IArchiveWorkspace workspace)
29삭제: {
30삭제: this.workspace = workspace;
31삭제: InitializeComponent();
32삭제: Availability.Text = workspace is IWorkspaceCapabilities features
33삭제: ? features.AvailabilityMessage
34삭제: : "작업 프로세스가 아직 연결되지 않았습니다. 파일을 처리할 수 없습니다.";
35삭제: UpdateActions();
36삭제: }
37삭제:
38삭제: private bool CanExecute(WorkspaceAction action, string format = "zip") =>
39삭제: workspace.IsAvailable && workspace is IWorkspaceCapabilities features && features.CanExecute(action, format);
40삭제:
41삭제: public async Task OpenStartupAsync(IReadOnlyList<string> arguments)
42삭제: {
43삭제: if (startupHandled) { return; }
44삭제: startupHandled = true;
45삭제: var target = ArchiveOpenArguments.Parse(arguments);
46삭제: if (target.Error is not null) { SetStatus(target.Error, true); return; }
47삭제: if (target.Path is null) { return; }
48삭제: if (phase != ScreenPhase.Idle)
49삭제: {
50삭제: SetStatus("다른 작업이 진행 중이라 시작 파일을 열지 못했습니다. 작업 후 파일 열기를 사용하세요.", true);
51삭제: return;
52삭제: }
53삭제: await SelectAndRun(WorkspaceAction.List, () => new WorkspaceRequest(
54삭제: Guid.NewGuid(), WorkspaceAction.List, [target.Path]));
55삭제: }
56삭제:
57삭제: private async void OpenArchive(object sender, RoutedEventArgs e)
58삭제: {
59삭제: await SelectAndRun(WorkspaceAction.List, () =>
60삭제: {
61삭제: var dialog = new OpenFileDialog
62삭제: {
63삭제: Title = "압축파일 열기",
64삭제: Filter = "ZIP 압축파일|*.zip",
65삭제: CheckFileExists = true
66삭제: };
67삭제: return dialog.ShowDialog(this) == true
68삭제: ? new WorkspaceRequest(Guid.NewGuid(), WorkspaceAction.List, [dialog.FileName])
69삭제: : null;
70삭제: });
71삭제: }
72삭제:
73삭제: private async void CreateArchive(object sender, RoutedEventArgs e)
74삭제: {
75삭제: await SelectAndRun(WorkspaceAction.Create, () =>
76삭제: {
77삭제: var sources = new OpenFileDialog
78삭제: {
79삭제: Title = "압축할 파일 선택",
80삭제: Multiselect = true,
81삭제: CheckFileExists = true
82삭제: };
83삭제: if (sources.ShowDialog(this) != true) { return null; }
84삭제: creationSources = sources.FileNames;
85삭제: creationDestination = null;
86삭제: CreationSelection.Text = $"선택한 생성 파일 {creationSources.Length:N0}개: {string.Join(", ", creationSources.Select(path => Path.GetFileName(path)))}";
87삭제: var destination = new SaveFileDialog
88삭제: {
89삭제: Title = "새 ZIP 파일 저장 위치",
90삭제: Filter = "ZIP 압축파일|*.zip",
91삭제: DefaultExt = ".zip",
92삭제: AddExtension = true,
93삭제: FileName = creationDestination ?? "새 압축파일.zip",
94삭제: OverwritePrompt = false
95삭제: };
96삭제: if (destination.ShowDialog(this) != true) { return null; }
97삭제: creationDestination = destination.FileName;
98삭제: CreationSelection.Text += $" → {Path.GetFileName(creationDestination)}";
99삭제: return new WorkspaceRequest(Guid.NewGuid(), WorkspaceAction.Create, creationSources, creationDestination);
100삭제: });
101삭제: }
102삭제:
103삭제: private async void RetryCreation(object sender, RoutedEventArgs e)
104삭제: {
105삭제: await SelectAndRun(WorkspaceAction.Create, () => creationSources.Length > 0 && creationDestination is not null
106삭제: ? new WorkspaceRequest(Guid.NewGuid(), WorkspaceAction.Create, creationSources, creationDestination)
107삭제: : null);
108삭제: }
109삭제:
110삭제: private async void ExtractArchive(object sender, RoutedEventArgs e)
111삭제: {
112삭제: await SelectAndRun(WorkspaceAction.Extract, () =>
113삭제: {
114삭제: if (archivePath is null) { SetStatus("먼저 ZIP 목록을 열어주세요.", true); return null; }
115삭제: var name = ExtractionName.Text;
116삭제: ZipExtractionWorkflow.ValidateFolderName(name);
117삭제: var parent = new OpenFolderDialog
118삭제: {
119삭제: Title = "새 결과 폴더를 만들 부모 위치 선택 (기존 폴더에 병합하지 않음)",
120삭제: Multiselect = false
121삭제: };
122삭제: if (parent.ShowDialog(this) != true) { return null; }
123삭제: var destination = Path.Combine(parent.FolderName, name);
124삭제: ExtractionSelection.Text = $"새 결과 폴더: {destination}";
125삭제: return new WorkspaceRequest(Guid.NewGuid(), WorkspaceAction.Extract, [archivePath], destination);
126삭제: });
127삭제: }
128삭제:
129삭제: private async Task SelectAndRun(WorkspaceAction action, Func<WorkspaceRequest?> select)
130삭제: {
131삭제: if (phase != ScreenPhase.Idle) { return; }
132삭제: if (!CanExecute(action))
133삭제: {
134삭제: SetStatus(action == WorkspaceAction.Extract
135삭제: ? "일반 압축 풀기는 비활성입니다. 명시적인 개발 검증 빌드와 작업자가 필요합니다."
136삭제: : "이 기능의 작업 프로세스가 연결되지 않았거나 지원하지 않습니다.", true);
137삭제: return;
138삭제: }
139삭제:
140삭제: // 파일 선택부터 결과 반영까지 같은 게이트를 유지함.
141삭제: phase = ScreenPhase.Selecting;
142삭제: UpdateActions();
143삭제: try
144삭제: {
145삭제: var request = select();
146삭제: if (request is null) { return; }
147삭제: if (request.Action == WorkspaceAction.List)
148삭제: {
149삭제: var target = request.Sources.Count == 1
150삭제: ? ArchiveOpenArguments.ValidatePath(request.Sources[0])
151삭제: : new ArchiveOpenTarget(null, "압축파일은 한 번에 하나만 열 수 있습니다.");
152삭제: if (target.Error is not null) { SetStatus(target.Error, true); return; }
153삭제: }
154삭제: await RunJob(request);
155삭제: }
156삭제: catch (ArchiveException error)
157삭제: {
158삭제: SetStatus(WorkspaceMessages.Error(error.Code), true);
159삭제: Progress.Value = 0;
160삭제: }
161삭제: catch (Exception)
162삭제: {
163삭제: // 파일 선택과 엔진 예외의 원문은 화면과 로그에 노출하지 않음.
164삭제: SetStatus("작업을 시작하지 못했습니다. 파일 상태를 확인하고 다시 선택하세요.", true);
165삭제: Progress.Value = 0;
166삭제: }
167삭제: finally
168삭제: {
169삭제: Progress.IsIndeterminate = false;
170삭제: activeJob = null;
171삭제: activeJobId = null;
172삭제: passwordRequests.Clear();
173삭제: phase = ScreenPhase.Idle;
174삭제: UpdateActions();
175삭제: }
176삭제: }
177삭제:
178삭제: private async Task RunJob(WorkspaceRequest request)
179삭제: {
180삭제: using var cancellation = new CancellationTokenSource();
181삭제: activeJob = cancellation;
182삭제: activeJobId = request.JobId;
183삭제: lastSequence = 0;
184삭제: passwordRequests.Clear();
185삭제: phase = ScreenPhase.Running;
186삭제: Progress.Value = 0;
187삭제: Progress.IsIndeterminate = true;
188삭제: ResultSummary.Text = "";
189삭제: UpdateActions();
190삭제: SetStatus(request.Action switch
191삭제: {
192삭제: WorkspaceAction.List => "파일 목록을 읽고 있습니다.",
193삭제: WorkspaceAction.Extract => "ZIP 무결성과 새 폴더 게시를 확인하고 있습니다.",
194삭제: _ => "파일을 압축하고 있습니다."
195삭제: });
196삭제:
197삭제: var progress = new Progress<WorkspaceProgress>(value => ApplyProgress(request.JobId, value));
198삭제: try
199삭제: {
200삭제: var result = await Task.Run(() => workspace.ExecuteAsync(
201삭제: request, progress, RequestPasswordAsync, cancellation.Token));
202삭제: phase = ScreenPhase.Finishing;
203삭제: UpdateActions();
204삭제: if (activeJobId != request.JobId || result.JobId != request.JobId)
205삭제: {
206삭제: throw new ArchiveException(ArchiveError.EngineFailure);
207삭제: }
208삭제:
209삭제: // 늦은 취소 토큰 대신 호스트의 실제 종료 결과를 사용함.
210삭제: PublishResult(request, result);
211삭제: }
212삭제: catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
213삭제: {
214삭제: phase = ScreenPhase.Finishing;
215삭제: Progress.Value = 0;
216삭제: SetStatus("중지 요청 후 작업이 종료되었습니다. 결과 파일 상태를 확인하세요.");
217삭제: }
218삭제: catch (ArchiveException error)
219삭제: {
220삭제: phase = ScreenPhase.Finishing;
221삭제: Progress.Value = 0;
222삭제: SetStatus(WorkspaceMessages.Error(error.Code), true);
223삭제: }
224삭제: catch (Exception)
225삭제: {
226삭제: phase = ScreenPhase.Finishing;
227삭제: Progress.Value = 0;
228삭제: SetStatus("파일을 처리하지 못했습니다. 파일 상태와 저장 위치를 확인하고 다시 시도하세요.", true);
229삭제: }
230삭제: finally
231삭제: {
232삭제: // 수명이 끝난 작업의 이벤트와 암호 요청을 결과 반영 이후 거부함.
233삭제: activeJobId = null;
234삭제: activeJob = null;
235삭제: Progress.IsIndeterminate = false;
236삭제: }
237삭제: }
238삭제:
239삭제: private void ApplyProgress(Guid jobId, WorkspaceProgress value)
240삭제: {
241삭제: if (activeJobId != jobId || value.JobId != jobId || value.Sequence <= lastSequence ||
242삭제: phase is ScreenPhase.Idle or ScreenPhase.Selecting or ScreenPhase.Finishing)
243삭제: {
244삭제: return;
245삭제: }
246삭제: lastSequence = value.Sequence;
247삭제: if (value.State is JobState.Completed or JobState.Partial or JobState.Cancelled or JobState.Failed)
248삭제: {
249삭제: phase = ScreenPhase.Finishing;
250삭제: Progress.IsIndeterminate = false;
251삭제: SetStatus("작업 결과와 정리를 확인하고 있습니다.");
252삭제: UpdateActions();
253삭제: return;
254삭제: }
255삭제: if (phase == ScreenPhase.Cancelling || activeJob?.IsCancellationRequested == true || value.State == JobState.Cancelling)
256삭제: {
257삭제: phase = ScreenPhase.Cancelling;
258삭제: SetStatus("중지 요청을 처리하고 있습니다.");
259삭제: Progress.IsIndeterminate = true;
260삭제: }
261삭제: else if (passwordWindow is not null || value.State == JobState.WaitingForPassword)
262삭제: {
263삭제: phase = ScreenPhase.WaitingForPassword;
264삭제: SetStatus("암호 입력을 기다리고 있습니다.");
265삭제: Progress.IsIndeterminate = false;
266삭제: }
267삭제: else
268삭제: {
269삭제: phase = ScreenPhase.Running;
270삭제: Progress.IsIndeterminate = value.TotalBytes is null or <= 0;
271삭제: if (value.TotalBytes > 0)
272삭제: {
273삭제: Progress.Value = Math.Clamp(100.0 * value.ProcessedBytes / value.TotalBytes.Value, 0, 100);
274삭제: }
275삭제: SetStatus($"처리한 크기: {Math.Max(0, value.ProcessedBytes):N0}바이트");
276삭제: }
277삭제: UpdateActions();
278삭제: }
279삭제:
280삭제: private void PublishResult(WorkspaceRequest request, WorkspaceResult result)
281삭제: {
282삭제: if (request.Action == WorkspaceAction.Extract)
283삭제: {
284삭제: var extractionPublished = result.Extraction is not null && ZipExtractionWorkflow.Published(result.Extraction);
285삭제: Progress.Value = extractionPublished ? 100 : 0;
286삭제: ResultSummary.Text = "열린 ZIP 목록과 이름/위치는 유지됩니다. 다른 새 위치는 압축 풀기 검증에서 선택하세요.";
287삭제: SetStatus(result.Extraction is not null ? ZipExtractionWorkflow.Describe(result.Extraction)
288삭제: : "새 결과 폴더의 게시를 확인하지 못했습니다.", !extractionPublished);
289삭제: return;
290삭제: }
291삭제: if (request.Action == WorkspaceAction.Create)
292삭제: {
293삭제: Progress.Value = result.Creation?.Publication?.Published == true ? 100 : 0;
294삭제: ResultSummary.Text = "생성에 사용한 선택은 유지됩니다. 다른 저장 이름은 새로 압축하기에서 선택하세요.";
295삭제: SetStatus(result.Creation is not null ? ZipCreationWorkflow.Describe(result.Creation)
296삭제: : "새 파일의 게시를 확인하지 못했습니다.", result.Creation?.Publication?.Published != true);
297삭제: return;
298삭제: }
299삭제: var succeeded = result.Outcome == WorkspaceOutcome.Completed && result.Error == ArchiveError.None;
300삭제: Progress.Value = succeeded ? 100 : 0;
301삭제: if (request.Action == WorkspaceAction.List && succeeded)
302삭제: {
303삭제: archivePath = request.Sources[0];
304삭제: ArchiveTitle.Text = Path.GetFileName(archivePath);
305삭제: Files.ItemsSource = result.Entries;
306삭제: EmptyState.Text = "이 압축파일에는 표시할 항목이 없습니다.";
307삭제: EmptyState.Visibility = result.Entries.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
308삭제: }
309삭제: var published = result.Entries.Count(entry => entry.Outcome == EntryOutcome.Extracted);
310삭제: var failed = result.Entries.Count(entry => entry.Outcome == EntryOutcome.Failed || entry.Error != ArchiveError.None);
311삭제: ResultSummary.Text = $"결과 항목 {result.Entries.Count:N0}개, 게시 확인 {published:N0}개, 실패 {failed:N0}개";
312삭제: if (succeeded)
313삭제: {
314삭제: SetStatus(request.Action == WorkspaceAction.List ? "파일 목록을 읽었습니다. 내용 검증은 별도입니다." : "ZIP 생성 작업이 완료되었습니다.");
315삭제: }
316삭제: else if (result.Outcome == WorkspaceOutcome.Cancelled && result.Error is ArchiveError.None or ArchiveError.Cancelled)
317삭제: {
318삭제: SetStatus("작업이 중지되었습니다. 결과 파일 상태를 확인하세요.");
319삭제: }
320삭제: else if (result.Outcome == WorkspaceOutcome.Partial)
321삭제: {
322삭제: SetStatus("일부 항목만 처리했습니다. 결과와 검증 상태를 확인하세요.", true);
323삭제: }
324삭제: else
325삭제: {
326삭제: SetStatus(WorkspaceMessages.Error(result.Error), true);
327삭제: }
328삭제: }
329삭제:
330삭제: private Task<SecureString?> RequestPasswordAsync(PasswordChallenge challenge, CancellationToken cancellationToken)
331삭제: {
332삭제: return Dispatcher.InvokeAsync<SecureString?>(() =>
333삭제: {
334삭제: cancellationToken.ThrowIfCancellationRequested();
335삭제: if (activeJobId != challenge.JobId || challenge.RequestId == Guid.Empty ||
336삭제: phase is ScreenPhase.Finishing or ScreenPhase.Cancelling || passwordWindow is not null ||
337삭제: !passwordRequests.Add(challenge.RequestId))
338삭제: {
339삭제: throw new ArchiveException(ArchiveError.InvalidPasswordResponse);
340삭제: }
341삭제:
342삭제: phase = ScreenPhase.WaitingForPassword;
343삭제: SetStatus(challenge.Attempt > 1 ? "암호를 다시 확인해 입력하세요." : "암호 입력을 기다리고 있습니다.");
344삭제: Progress.IsIndeterminate = false;
345삭제: var dialog = new PasswordWindow { Owner = this };
346삭제: passwordWindow = dialog;
347삭제: UpdateActions();
348삭제: using var registration = cancellationToken.Register(() =>
349삭제: Dispatcher.BeginInvoke(new Action(() =>
350삭제: {
351삭제: if (dialog.IsVisible) { dialog.Close(); }
352삭제: })));
353삭제: try
354삭제: {
355삭제: cancellationToken.ThrowIfCancellationRequested();
356삭제: if (dialog.ShowDialog() == true && !cancellationToken.IsCancellationRequested && activeJobId == challenge.JobId)
357삭제: {
358삭제: return dialog.TakePassword();
359삭제: }
360삭제: RequestStop();
361삭제: return null;
362삭제: }
363삭제: finally
364삭제: {
365삭제: dialog.DiscardPassword();
366삭제: passwordWindow = null;
367삭제: if (phase != ScreenPhase.Finishing)
368삭제: {
369삭제: phase = activeJob?.IsCancellationRequested == true ? ScreenPhase.Cancelling : ScreenPhase.Running;
370삭제: SetStatus(phase == ScreenPhase.Cancelling ? "중지 요청을 처리하고 있습니다." : "작업을 계속하고 있습니다.");
371삭제: Progress.IsIndeterminate = true;
372삭제: }
373삭제: UpdateActions();
374삭제: }
375삭제: }).Task;
376삭제: }
377삭제:
378삭제: private void StopJob(object sender, RoutedEventArgs e) => RequestStop();
379삭제:
380삭제: private void RequestStop()
381삭제: {
382삭제: if (activeJob is null || phase == ScreenPhase.Finishing) { return; }
383삭제: phase = ScreenPhase.Cancelling;
384삭제: try { activeJob.Cancel(); }
385삭제: catch (AggregateException)
386삭제: {
387삭제: // 취소 관찰자 실패가 있어도 실제 작업 종료를 기다림.
388삭제: }
389삭제: SetStatus("중지 요청을 처리하고 있습니다.");
390삭제: UpdateActions();
391삭제: }
392삭제:
393삭제: private void UpdateActions()
394삭제: {
395삭제: var ready = phase == ScreenPhase.Idle;
396삭제: OpenButton.IsEnabled = ready && CanExecute(WorkspaceAction.List);
397삭제: CreateButton.IsEnabled = ready && CanExecute(WorkspaceAction.Create);
398삭제: CreateButton.Content = ZipCreationWorkflow.ValidationEnabled ? "ZIP 생성 검증" : "새로 압축하기";
399삭제: CreateButton.ToolTip = ZipCreationWorkflow.ScopeMessage;
400삭제: RetryCreateButton.IsEnabled = ready && CanExecute(WorkspaceAction.Create) &&
401삭제: creationSources.Length > 0 && creationDestination is not null;
402삭제: ExtractButton.IsEnabled = ready && archivePath is not null && CanExecute(WorkspaceAction.Extract);
403삭제: ExtractButton.Content = ZipExtractionWorkflow.ValidationEnabled ? "압축 풀기 검증" : "압축 풀기";
404삭제: ExtractButton.ToolTip = ZipExtractionWorkflow.ScopeMessage;
405삭제: ExtractionName.IsEnabled = ready && CanExecute(WorkspaceAction.Extract);
406삭제: StopButton.IsEnabled = activeJob is not null &&
407삭제: phase is ScreenPhase.Running or ScreenPhase.WaitingForPassword;
408삭제: }
409삭제:
410삭제: private void SetStatus(string message, bool error = false)
411삭제: {
412삭제: Status.Text = message;
413삭제: Status.Foreground = error ? new SolidColorBrush(Color.FromRgb(164, 38, 44)) : SystemColors.ControlTextBrush;
414삭제: }
415삭제:
416삭제: private void ShowInstallation(object sender, RoutedEventArgs e)
417삭제: {
418삭제: MessageBox.Show(this,
419삭제: "설치 파일은 준비 중입니다.\n\n예정 흐름: 설치 파일 더블클릭 → 설치 → 완료\n\n기본 앱은 설치 후 Windows 설정에서 직접 선택합니다. 현재 화면은 설정을 변경하지 않습니다.",
420삭제: "설치와 기본 앱 설정", MessageBoxButton.OK, MessageBoxImage.Information);
421삭제: }
422삭제:
423삭제: private void OnClosing(object? sender, CancelEventArgs e)
424삭제: {
425삭제: if (phase != ScreenPhase.Idle)
426삭제: {
427삭제: e.Cancel = true;
428삭제: RequestStop();
429삭제: SetStatus("파일 선택이나 작업 정리가 끝난 뒤 창을 닫아주세요.");
430삭제: }
431삭제: }
432삭제: }
삭제src/Zipelo.Desktop/PasswordWindow.xaml+0-17
@@ -1,17 +0,0 @@
1삭제: <Window x:Class="Zipelo.Desktop.PasswordWindow"
2삭제: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3삭제: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4삭제: Title="암호 입력" SizeToContent="WidthAndHeight" ResizeMode="NoResize"
5삭제: WindowStartupLocation="CenterOwner" MinWidth="400">
6삭제: <StackPanel Margin="28" MaxWidth="460">
7삭제: <TextBlock Text="이 파일의 암호를 입력하세요." FontSize="20" FontWeight="SemiBold" />
8삭제: <Label Content="암호" Target="{Binding ElementName=Secret}" Margin="0,16,0,0" />
9삭제: <PasswordBox x:Name="Secret" MinHeight="44" Padding="8" MaxLength="1024"
10삭제: AutomationProperties.Name="압축파일 암호" />
11삭제: <TextBlock Text="암호를 저장하지 않습니다." Margin="0,12,0,20" />
12삭제: <WrapPanel>
13삭제: <Button Content="확인" IsDefault="True" Click="AcceptPassword" />
14삭제: <Button Content="취소" IsCancel="True" />
15삭제: </WrapPanel>
16삭제: </StackPanel>
17삭제: </Window>
삭제src/Zipelo.Desktop/PasswordWindow.xaml.cs+0-38
@@ -1,38 +0,0 @@
1삭제: using System.Security;
2삭제: using System.Windows;
3삭제:
4삭제: namespace Zipelo.Desktop;
5삭제:
6삭제: public partial class PasswordWindow : Window
7삭제: {
8삭제: public SecureString? SubmittedPassword { get; private set; }
9삭제:
10삭제: public PasswordWindow()
11삭제: {
12삭제: InitializeComponent();
13삭제: Loaded += (_, _) => Secret.Focus();
14삭제: Closed += (_, _) => Secret.Clear();
15삭제: }
16삭제:
17삭제: public SecureString? TakePassword()
18삭제: {
19삭제: var password = SubmittedPassword;
20삭제: SubmittedPassword = null;
21삭제: return password;
22삭제: }
23삭제:
24삭제: public void DiscardPassword()
25삭제: {
26삭제: SubmittedPassword?.Dispose();
27삭제: SubmittedPassword = null;
28삭제: Secret.Clear();
29삭제: }
30삭제:
31삭제: private void AcceptPassword(object sender, RoutedEventArgs e)
32삭제: {
33삭제: SubmittedPassword = Secret.SecurePassword;
34삭제: SubmittedPassword.MakeReadOnly();
35삭제: Secret.Clear();
36삭제: DialogResult = true;
37삭제: }
38삭제: }
삭제src/Zipelo.Desktop/Properties/PublishProfiles/WindowsX64.pubxml+0-9
@@ -1,9 +0,0 @@
1삭제: <Project>
2삭제: <PropertyGroup>
3삭제: <Configuration>Release</Configuration>
4삭제: <RuntimeIdentifier>win-x64</RuntimeIdentifier>
5삭제: <SelfContained>true</SelfContained>
6삭제: <PublishSingleFile>false</PublishSingleFile>
7삭제: <PublishTrimmed>false</PublishTrimmed>
8삭제: </PropertyGroup>
9삭제: </Project>
삭제src/Zipelo.Desktop/WorkerDeployment.targets+0-67
@@ -1,67 +0,0 @@
1삭제: <Project>
2삭제: <PropertyGroup>
3삭제: <!-- 명시적으로 전달하는 게시 속성을 제거 목록에 중복하지 않음. -->
4삭제: <_ZipeloWorkerPublishRemoveProperties>PublishProfile;PublishProfileFullPath;PublishUrl;OutputPath;OutDir;BaseOutputPath;BaseIntermediateOutputPath;IntermediateOutputPath;TargetDir;NoBuild;PublishSelfContained</_ZipeloWorkerPublishRemoveProperties>
5삭제: <_ZipeloWorkerProject>$(MSBuildThisFileDirectory)../Zipelo.Worker/Zipelo.Worker.csproj</_ZipeloWorkerProject>
6삭제: </PropertyGroup>
7삭제:
8삭제: <Target Name="PrepareZipeloWorkerDeployment">
9삭제: <PropertyGroup>
10삭제: <_ZipeloWorkerSelfContained Condition="'$(SelfContained)' == ''">false</_ZipeloWorkerSelfContained>
11삭제: <_ZipeloWorkerSelfContained Condition="'$(SelfContained)' != ''">$(SelfContained)</_ZipeloWorkerSelfContained>
12삭제: </PropertyGroup>
13삭제: </Target>
14삭제:
15삭제: <!-- 개발 빌드의 작업자 출력을 앱 기준 고정 하위 폴더에 배치함. -->
16삭제: <Target Name="StageZipeloWorkerForBuild" AfterTargets="Build" DependsOnTargets="PrepareZipeloWorkerDeployment"
17삭제: Condition="'$(DesignTimeBuild)' != 'true' And ('$(OS)' == 'Windows_NT' Or '$(RuntimeIdentifier)' == 'win-x64')">
18삭제: <MSBuild Projects="$(_ZipeloWorkerProject)" Targets="GetTargetPath"
19삭제: RemoveProperties="TargetFramework;PublishProfile;PublishProfileFullPath;PublishDir;OutputPath;OutDir;BaseOutputPath;BaseIntermediateOutputPath;IntermediateOutputPath;TargetDir"
20삭제: Properties="Configuration=$(Configuration);TargetFramework=net10.0;RuntimeIdentifier=$(RuntimeIdentifier);SelfContained=$(_ZipeloWorkerSelfContained);UseAppHost=true">
21삭제: <Output TaskParameter="TargetOutputs" ItemName="_ZipeloWorkerTargetPath" />
22삭제: </MSBuild>
23삭제: <Error Condition="'@(_ZipeloWorkerTargetPath)' == ''" Text="작업자 출력 위치를 확인하지 못했습니다." />
24삭제: <PropertyGroup>
25삭제: <_ZipeloWorkerBuildDirectory>@(_ZipeloWorkerTargetPath->'%(RootDir)%(Directory)')</_ZipeloWorkerBuildDirectory>
26삭제: </PropertyGroup>
27삭제: <ItemGroup>
28삭제: <_ZipeloWorkerBuildFile Include="$(_ZipeloWorkerBuildDirectory)**/*"
29삭제: Exclude="$(_ZipeloWorkerBuildDirectory)publish/**/*" />
30삭제: </ItemGroup>
31삭제: <Error Condition="!Exists('$(_ZipeloWorkerBuildDirectory)Zipelo.Worker.exe') Or !Exists('$(_ZipeloWorkerBuildDirectory)Zipelo.Worker.dll') Or !Exists('$(_ZipeloWorkerBuildDirectory)Zipelo.Worker.runtimeconfig.json') Or !Exists('$(_ZipeloWorkerBuildDirectory)Zipelo.Worker.deps.json') Or !Exists('$(_ZipeloWorkerBuildDirectory)Zipelo.Core.dll') Or !Exists('$(_ZipeloWorkerBuildDirectory)Zipelo.Runtime.dll')"
32삭제: Text="작업자 필수 빌드 파일이 누락되었습니다. Desktop과 작업자를 같은 구성으로 빌드하세요." />
33삭제: <Copy SourceFiles="@(_ZipeloWorkerBuildFile)"
34삭제: DestinationFiles="@(_ZipeloWorkerBuildFile->'$(TargetDir)worker/%(RecursiveDir)%(Filename)%(Extension)')"
35삭제: SkipUnchangedFiles="true" />
36삭제: </Target>
37삭제:
38삭제: <!-- 최종 배치는 UI 게시 위치 아래에 SDK가 같은 RID로 별도 게시하도록 함. -->
39삭제: <Target Name="PublishZipeloWorker" AfterTargets="Publish" DependsOnTargets="PrepareZipeloWorkerDeployment"
40삭제: Condition="'$(DesignTimeBuild)' != 'true' And ('$(OS)' == 'Windows_NT' Or '$(RuntimeIdentifier)' == 'win-x64')">
41삭제: <Error Condition="'$(PublishDir)' == ''" Text="Windows UI 게시 출력 디렉터리가 비어 있습니다." />
42삭제: <PropertyGroup>
43삭제: <_ZipeloWorkerPublishSelfContained>$(_ZipeloWorkerSelfContained)</_ZipeloWorkerPublishSelfContained>
44삭제: <_ZipeloWorkerPublishSelfContained Condition="'$(PublishSelfContained)' != ''">$(PublishSelfContained)</_ZipeloWorkerPublishSelfContained>
45삭제: <_ZipeloWorkerPublishStage>$([System.IO.Path]::GetFullPath('$(IntermediateOutputPath)', '$(MSBuildProjectDirectory)'))/zipelo-worker-publish/$([System.Guid]::NewGuid())/</_ZipeloWorkerPublishStage>
46삭제: <_ZipeloWorkerPublishDirectory>$([System.IO.Path]::GetFullPath('$(PublishDir)', '$(MSBuildProjectDirectory)'))/worker/</_ZipeloWorkerPublishDirectory>
47삭제: </PropertyGroup>
48삭제: <!-- 이번 게시의 새 SDK 출력만 수집하며 이전 bin/publish를 검색하지 않음. -->
49삭제: <MakeDir Directories="$(_ZipeloWorkerPublishStage)" />
50삭제: <MSBuild Projects="$(_ZipeloWorkerProject)" Targets="Publish"
51삭제: RemoveProperties="$(_ZipeloWorkerPublishRemoveProperties)"
52삭제: Properties="Configuration=$(Configuration);TargetFramework=net10.0;RuntimeIdentifier=$(RuntimeIdentifier);SelfContained=$(_ZipeloWorkerPublishSelfContained);UseAppHost=true;PublishSingleFile=false;PublishTrimmed=false;PublishAot=false;PublishDir=$(_ZipeloWorkerPublishStage)" />
53삭제: <ItemGroup>
54삭제: <_ZipeloWorkerPublishRequired Include="$(_ZipeloWorkerPublishStage)Zipelo.Worker.exe;$(_ZipeloWorkerPublishStage)Zipelo.Worker.dll;$(_ZipeloWorkerPublishStage)Zipelo.Worker.deps.json;$(_ZipeloWorkerPublishStage)Zipelo.Worker.runtimeconfig.json;$(_ZipeloWorkerPublishStage)Zipelo.Core.dll;$(_ZipeloWorkerPublishStage)Zipelo.Runtime.dll" />
55삭제: <_ZipeloWorkerPublishRequired Include="$(_ZipeloWorkerPublishStage)System.Private.CoreLib.dll;$(_ZipeloWorkerPublishStage)coreclr.dll;$(_ZipeloWorkerPublishStage)clrjit.dll;$(_ZipeloWorkerPublishStage)hostfxr.dll;$(_ZipeloWorkerPublishStage)hostpolicy.dll"
56삭제: Condition="'$(_ZipeloWorkerPublishSelfContained)' == 'true'" />
57삭제: </ItemGroup>
58삭제: <Error Condition="!Exists('%(_ZipeloWorkerPublishRequired.Identity)')" Text="Windows 작업자 필수 게시 파일이 누락되었습니다: %(_ZipeloWorkerPublishRequired.Filename)%(_ZipeloWorkerPublishRequired.Extension)" />
59삭제: <ItemGroup>
60삭제: <_ZipeloWorkerPublishedFile Include="$(_ZipeloWorkerPublishStage)**/*" />
61삭제: </ItemGroup>
62삭제: <Copy SourceFiles="@(_ZipeloWorkerPublishedFile)"
63삭제: DestinationFiles="@(_ZipeloWorkerPublishedFile->'$(_ZipeloWorkerPublishDirectory)%(RecursiveDir)%(Filename)%(Extension)')"
64삭제: SkipUnchangedFiles="false" />
65삭제: <RemoveDir Directories="$(_ZipeloWorkerPublishStage)" />
66삭제: </Target>
67삭제: </Project>
삭제src/Zipelo.Desktop/WorkspaceMessages.cs+0-23
@@ -1,23 +0,0 @@
1삭제: using Zipelo.Core;
2삭제:
3삭제: namespace Zipelo.Desktop;
4삭제:
5삭제: internal static class WorkspaceMessages
6삭제: {
7삭제: public static string Error(ArchiveError code) => code switch
8삭제: {
9삭제: ArchiveError.EngineUnavailable => "작업 프로세스를 시작할 수 없습니다. Zipelo 폴더 전체를 확인한 뒤 다시 실행하세요.",
10삭제: ArchiveError.EngineFailure => "작업 프로세스가 정상 결과를 반환하지 못했습니다. ZIP 파일 상태와 Zipelo 폴더를 확인한 뒤 다시 여세요.",
11삭제: ArchiveError.UnsupportedOperation => "이 형식 또는 기능은 현재 연결된 엔진에서 지원하지 않습니다.",
12삭제: ArchiveError.UnsafePath => "안전하게 저장할 수 없는 파일 경로가 포함되어 작업을 중단했습니다.",
13삭제: ArchiveError.UnsupportedEntry => "현재 처리할 수 없는 파일 항목이 포함되어 있습니다.",
14삭제: ArchiveError.OutputUnavailable => "저장 또는 정리를 완료하지 못했습니다. 결과 위치를 확인하세요.",
15삭제: ArchiveError.OutputConflict => "저장할 이름이 기존 파일과 충돌합니다. 다른 이름이나 위치를 선택하세요.",
16삭제: ArchiveError.BudgetExceeded => "안전한 처리 한도를 초과했습니다. 더 작은 파일로 다시 시도하세요.",
17삭제: ArchiveError.PasswordAttemptsExceeded => "암호 입력 횟수 한도에 도달했습니다. 암호를 확인한 뒤 다시 여세요.",
18삭제: ArchiveError.InvalidPasswordResponse => "암호 요청을 연결하지 못했습니다. 파일을 다시 여세요.",
19삭제: ArchiveError.IntegrityFailure => "일부 데이터가 검증을 통과하지 못했습니다. 정상 파일로 간주하지 마세요.",
20삭제: ArchiveError.Cancelled => "중지 후 정리를 완료하지 못했습니다. 결과 위치를 확인하세요.",
21삭제: _ => "작업에 실패했습니다. 파일 상태와 저장 위치를 확인하고 다시 시도하세요."
22삭제: };
23삭제: }
삭제src/Zipelo.Desktop/WorkspacePort.cs+0-94
@@ -1,94 +0,0 @@
1삭제: using System.Security;
2삭제: using Zipelo.Core;
3삭제:
4삭제: namespace Zipelo.Desktop;
5삭제:
6삭제: public enum WorkspaceAction
7삭제: {
8삭제: List,
9삭제: Extract,
10삭제: Create
11삭제: }
12삭제:
13삭제: public enum WorkspaceOutcome
14삭제: {
15삭제: Completed,
16삭제: Partial,
17삭제: Cancelled,
18삭제: Failed
19삭제: }
20삭제:
21삭제: public sealed record WorkspaceRequest(
22삭제: Guid JobId,
23삭제: WorkspaceAction Action,
24삭제: IReadOnlyList<string> Sources,
25삭제: string? Destination = null)
26삭제: {
27삭제: public string Format { get; init; } = "zip";
28삭제: }
29삭제:
30삭제: public sealed record FileRow(string Name, string Size, string Verification)
31삭제: {
32삭제: public string EntryId { get; init; } = "";
33삭제: public EntryKind Kind { get; init; }
34삭제: public EntryOutcome Outcome { get; init; }
35삭제: public ArchiveError Error { get; init; }
36삭제: }
37삭제:
38삭제: public sealed record WorkspaceProgress(long ProcessedBytes, long? TotalBytes)
39삭제: {
40삭제: public Guid JobId { get; init; }
41삭제: public long Sequence { get; init; }
42삭제: public JobState State { get; init; } = JobState.Running;
43삭제: }
44삭제:
45삭제: public sealed record PasswordChallenge(Guid JobId, Guid RequestId)
46삭제: {
47삭제: public int Attempt { get; init; } = 1;
48삭제: }
49삭제:
50삭제: public sealed record WorkspaceResult(
51삭제: WorkspaceOutcome Outcome,
52삭제: IReadOnlyList<FileRow> Entries)
53삭제: {
54삭제: public Guid JobId { get; init; }
55삭제: public ArchiveError Error { get; init; }
56삭제: public Zipelo.Ui.CreationResult? Creation { get; init; }
57삭제: public Zipelo.Ui.ExtractionResult? Extraction { get; init; }
58삭제: }
59삭제:
60삭제: // UI 측 연결 경계임. 실제 코어 계약과 연결하는 어댑터는 별도 구현함.
61삭제: public interface IArchiveWorkspace
62삭제: {
63삭제: bool IsAvailable { get; }
64삭제:
65삭제: Task<WorkspaceResult> ExecuteAsync(
66삭제: WorkspaceRequest request,
67삭제: IProgress<WorkspaceProgress> progress,
68삭제: Func<PasswordChallenge, CancellationToken, Task<SecureString?>> requestPassword,
69삭제: CancellationToken cancellationToken);
70삭제: }
71삭제:
72삭제: public sealed class UnavailableWorkspace : IArchiveWorkspace, IWorkspaceCapabilities
73삭제: {
74삭제: public bool IsAvailable => false;
75삭제: public string AvailabilityMessage { get; internal set; } =
76삭제: "작업 프로세스가 아직 연결되지 않았습니다. 파일을 처리할 수 없습니다.";
77삭제: public bool CanExecute(WorkspaceAction action, string format) => false;
78삭제:
79삭제: public Task<WorkspaceResult> ExecuteAsync(
80삭제: WorkspaceRequest request,
81삭제: IProgress<WorkspaceProgress> progress,
82삭제: Func<PasswordChallenge, CancellationToken, Task<SecureString?>> requestPassword,
83삭제: CancellationToken cancellationToken)
84삭제: {
85삭제: throw new NotSupportedException("압축 엔진이 아직 연결되지 않았습니다.");
86삭제: }
87삭제: }
88삭제:
89삭제: // 기능 조회는 실제 연결된 호스트가 제공함. 해제 검증 전에는 해제 능력을 게시하지 않음.
90삭제: public interface IWorkspaceCapabilities
91삭제: {
92삭제: bool CanExecute(WorkspaceAction action, string format);
93삭제: string AvailabilityMessage { get; }
94삭제: }
삭제src/Zipelo.Desktop/ZipCreationWorkflow.cs+0-101
@@ -1,101 +0,0 @@
1삭제: using System.IO;
2삭제: using Zipelo.Core;
3삭제: using Zipelo.Runtime;
4삭제:
5삭제: namespace Zipelo.Ui;
6삭제:
7삭제: public sealed record CreationSource(string Name, Func<CancellationToken, Task<Stream>> OpenRead);
8삭제: public sealed record CreationResult(JobResult Job, ZipPublicationResult? Publication);
9삭제:
10삭제: public static class ZipCreationWorkflow
11삭제: {
12삭제: #if ZIPELO_CREATION_VALIDATION
13삭제: public static bool ValidationEnabled => true;
14삭제: #else
15삭제: public static bool ValidationEnabled => false;
16삭제: #endif
17삭제: public const string ScopeMessage = "개발 검증용: 파일 최대 1,024개, 합계 16 MiB, 새 ZIP만 저장합니다. 폴더, 암호, 분할은 지원하지 않습니다.";
18삭제:
19삭제: public static async Task<CreationResult> RunAsync(ZipWorkerClient client, Guid jobId,
20삭제: IReadOnlyList<CreationSource> sources, string destination, CancellationToken cancellationToken)
21삭제: {
22삭제: if (!ValidationEnabled || !NewZipPublisher.IsSupportedPlatform)
23삭제: {
24삭제: throw new ArchiveException(ArchiveError.UnsupportedOperation);
25삭제: }
26삭제: if (sources.Count is < 1 or > 1024 || !Path.IsPathFullyQualified(destination))
27삭제: {
28삭제: throw new ArchiveException(ArchiveError.BudgetExceeded);
29삭제: }
30삭제: using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
31삭제: deadline.CancelAfter(TimeSpan.FromMinutes(2));
32삭제: var token = deadline.Token;
33삭제: var snapshots = new List<MemoryStream>();
34삭제: var inputs = new List<ZipCreateInput>();
35삭제: var names = new HashSet<string>(OutputPathPolicy.Comparer(OutputPathPolicy.CurrentPolicy));
36삭제: long total = 0;
37삭제: try
38삭제: {
39삭제: var buffer = new byte[65536];
40삭제: foreach (var source in sources)
41삭제: {
42삭제: token.ThrowIfCancellationRequested();
43삭제: if (source.Name.Length > 1024 ||
44삭제: OutputPathPolicy.Validate(source.Name, OutputPathPolicy.CurrentPolicy).Count != 1 ||
45삭제: !names.Add(source.Name))
46삭제: {
47삭제: throw new ArchiveException(ArchiveError.UnsafePath);
48삭제: }
49삭제: await using var input = await source.OpenRead(token).ConfigureAwait(false);
50삭제: using var snapshot = new MemoryStream();
51삭제: int count;
52삭제: while ((count = await input.ReadAsync(buffer.AsMemory(), token).ConfigureAwait(false)) != 0)
53삭제: {
54삭제: total += count;
55삭제: if (total > 16L * 1024 * 1024) { throw new ArchiveException(ArchiveError.BudgetExceeded); }
56삭제: await snapshot.WriteAsync(buffer.AsMemory(0, count), token).ConfigureAwait(false);
57삭제: }
58삭제: // Runtime requires read-only inputs; keep writable staging private.
59삭제: var readOnlySnapshot = new MemoryStream(snapshot.ToArray(), writable: false);
60삭제: snapshots.Add(readOnlySnapshot);
61삭제: inputs.Add(new ZipCreateInput(source.Name, readOnlySnapshot));
62삭제: }
63삭제: var limits = new JobLimits(1024, 16L * 1024 * 1024, 16L * 1024 * 1024,
64삭제: TimeSpan.FromMinutes(2), 3);
65삭제: var result = await client.CreateAsync(jobId, inputs, limits, new ZipCreationOptions(), token)
66삭제: .ConfigureAwait(false);
67삭제: if (result.Job.JobId != jobId) { throw new ArchiveException(ArchiveError.EngineFailure); }
68삭제: if (result.Job.State != JobState.Completed || result.Job.Error != ArchiveError.None)
69삭제: {
70삭제: return new CreationResult(result.Job, null);
71삭제: }
72삭제: var publication = await NewZipPublisher.PublishAsync(result, destination, token).ConfigureAwait(false);
73삭제: return new CreationResult(result.Job, publication);
74삭제: }
75삭제: catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested && deadline.IsCancellationRequested)
76삭제: {
77삭제: throw new ArchiveException(ArchiveError.BudgetExceeded);
78삭제: }
79삭제: finally
80삭제: {
81삭제: foreach (var snapshot in snapshots) { snapshot.Dispose(); }
82삭제: }
83삭제: }
84삭제:
85삭제: public static string Describe(CreationResult result)
86삭제: {
87삭제: if (result.Publication is { Published: true }) { return "새 ZIP 파일을 저장했습니다. 기존 파일은 덮어쓰지 않았습니다."; }
88삭제: if (result.Publication is { CleanupFailed: true })
89삭제: {
90삭제: return "ZIP 저장에 실패했고 임시 파일 정리도 완료하지 못했습니다. 선택한 저장 폴더를 확인하세요.";
91삭제: }
92삭제: var error = result.Publication?.Error ?? result.Job.Error;
93삭제: return error switch
94삭제: {
95삭제: ArchiveError.Cancelled => "생성이 중지되었습니다. 새 ZIP 파일은 게시되지 않았습니다.",
96삭제: ArchiveError.OutputConflict => "같은 이름의 파일이 있습니다. 기존 파일을 유지했습니다. 새 이름을 선택하세요.",
97삭제: ArchiveError.BudgetExceeded => "파일 크기나 처리 시간 한도를 초과했습니다. 더 작은 파일로 시도하세요.",
98삭제: _ => "새 ZIP 파일을 저장하지 못했습니다. 파일과 저장 위치를 확인하고 다시 시도하세요."
99삭제: };
100삭제: }
101삭제: }
삭제src/Zipelo.Desktop/ZipExtractionWorkflow.cs+0-112
@@ -1,112 +0,0 @@
1삭제: using System.IO;
2삭제: using Zipelo.Core;
3삭제: using Zipelo.Runtime;
4삭제:
5삭제: namespace Zipelo.Ui;
6삭제:
7삭제: public sealed record ExtractionResult(JobResult Job, ZipPublicationResult? Publication);
8삭제:
9삭제: public static class ZipExtractionWorkflow
10삭제: {
11삭제: #if ZIPELO_EXTRACTION_VALIDATION
12삭제: public static bool ValidationEnabled => true;
13삭제: #else
14삭제: public static bool ValidationEnabled => false;
15삭제: #endif
16삭제: public const string ScopeMessage = "개발 검증용: ZIP 입력/해제 합계 각각 16 MiB, 최대 1,024항목, 2분 한도입니다. 새 폴더만 게시하며 암호/분할/다른 형식은 지원하지 않습니다.";
17삭제:
18삭제: public static bool Published(ExtractionResult result) =>
19삭제: result.Job.State == JobState.Completed && result.Job.Error == ArchiveError.None &&
20삭제: result.Publication is { Published: true, Error: ArchiveError.None, CleanupFailed: false };
21삭제:
22삭제: public static void ValidateFolderName(string name)
23삭제: {
24삭제: if (string.IsNullOrWhiteSpace(name) || name.Length > 128 ||
25삭제: OutputPathPolicy.Validate(name, OutputPathPolicy.CurrentPolicy).Count != 1)
26삭제: {
27삭제: throw new ArchiveException(ArchiveError.UnsafePath);
28삭제: }
29삭제: }
30삭제:
31삭제: public static async Task<ExtractionResult> RunAsync(ZipWorkerClient client, Guid jobId,
32삭제: Func<CancellationToken, Task<Stream>> openRead, string destination, CancellationToken cancellationToken)
33삭제: {
34삭제: if (!ValidationEnabled || !NewFolderPublisher.IsSupportedPlatform || !client.SupportsMemoryExtraction)
35삭제: {
36삭제: throw new ArchiveException(ArchiveError.UnsupportedOperation);
37삭제: }
38삭제: if (!Path.IsPathFullyQualified(destination)) { throw new ArchiveException(ArchiveError.UnsafePath); }
39삭제: ValidateFolderName(Path.GetFileName(destination));
40삭제: using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
41삭제: deadline.CancelAfter(TimeSpan.FromMinutes(2));
42삭제: var token = deadline.Token;
43삭제: try
44삭제: {
45삭제: token.ThrowIfCancellationRequested();
46삭제: using var staging = new MemoryStream();
47삭제: await using (var input = await openRead(token).ConfigureAwait(false))
48삭제: {
49삭제: if (!input.CanRead || input.CanWrite) { throw new ArchiveException(ArchiveError.UnsupportedOperation); }
50삭제: var buffer = new byte[65536];
51삭제: int count;
52삭제: while ((count = await input.ReadAsync(buffer.AsMemory(), token).ConfigureAwait(false)) != 0)
53삭제: {
54삭제: if (staging.Length + count > 16L * 1024 * 1024)
55삭제: {
56삭제: throw new ArchiveException(ArchiveError.BudgetExceeded);
57삭제: }
58삭제: await staging.WriteAsync(buffer.AsMemory(0, count), token).ConfigureAwait(false);
59삭제: }
60삭제: }
61삭제: // 동일한 제한 스냅샷을 읽기 전용으로 작업자에 전달함.
62삭제: using var snapshot = new MemoryStream(staging.ToArray(), writable: false);
63삭제: var limits = new JobLimits(1024, 16L * 1024 * 1024, 16L * 1024 * 1024,
64삭제: TimeSpan.FromMinutes(2), 3);
65삭제: var result = await client.ExtractAsync(jobId, snapshot, limits, token).ConfigureAwait(false);
66삭제: if (result.Job.JobId != jobId) { throw new ArchiveException(ArchiveError.EngineFailure); }
67삭제: if (result.Job.Error == ArchiveError.Cancelled && !cancellationToken.IsCancellationRequested &&
68삭제: deadline.IsCancellationRequested)
69삭제: {
70삭제: result = result with { Job = result.Job with { State = JobState.Failed, Error = ArchiveError.BudgetExceeded } };
71삭제: }
72삭제: if (result.Job.State != JobState.Completed || result.Job.Error != ArchiveError.None)
73삭제: {
74삭제: return new ExtractionResult(result.Job, null);
75삭제: }
76삭제: var publication = await NewFolderPublisher.PublishAsync(result, destination, token).ConfigureAwait(false);
77삭제: if (!publication.Published && publication.Error == ArchiveError.Cancelled &&
78삭제: !cancellationToken.IsCancellationRequested && deadline.IsCancellationRequested)
79삭제: {
80삭제: publication = publication with { Error = ArchiveError.BudgetExceeded };
81삭제: }
82삭제: // 게시 이후에는 늦은 취소보다 실제 게시 결과를 우선함.
83삭제: return new ExtractionResult(result.Job, publication);
84삭제: }
85삭제: catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested && deadline.IsCancellationRequested)
86삭제: {
87삭제: throw new ArchiveException(ArchiveError.BudgetExceeded);
88삭제: }
89삭제: }
90삭제:
91삭제: public static string Describe(ExtractionResult result)
92삭제: {
93삭제: if (result.Publication is { CleanupFailed: true })
94삭제: {
95삭제: return "압축 풀기 또는 임시 결과 정리가 완료되지 않았습니다. 선택한 부모 폴더의 임시 항목을 확인하세요. 원본과 기존 대상은 덮어쓰지 않았습니다.";
96삭제: }
97삭제: if (Published(result)) { return "검증한 내용을 새 결과 폴더에 게시했습니다. 기존 파일/폴더는 덮어쓰지 않았습니다."; }
98삭제: var error = result.Publication?.Error ?? result.Job.Error;
99삭제: return error switch
100삭제: {
101삭제: ArchiveError.Cancelled => "압축 풀기가 중지되었습니다. 새 결과 폴더는 게시되지 않았습니다.",
102삭제: ArchiveError.OutputConflict => "같은 이름의 대상이 있거나 ZIP 내부 이름이 충돌합니다. 기존 대상은 유지됩니다. 다른 새 폴더 이름/위치를 선택하거나 ZIP을 확인하세요.",
103삭제: ArchiveError.OutputUnavailable => "이 위치에 안전하게 게시할 수 없습니다. 권한과 지원 파일시스템을 확인하고 다른 부모 폴더를 선택하세요.",
104삭제: ArchiveError.UnsafePath => "안전하지 않은 경로나 링크 조건으로 게시하지 않았습니다. ZIP과 새 저장 위치를 확인하세요.",
105삭제: ArchiveError.UnsupportedEntry => "링크 또는 지원하지 않는 항목이 있어 게시하지 않았습니다.",
106삭제: ArchiveError.IntegrityFailure => "CRC/길이 등 무결성 검증에 실패해 게시하지 않았습니다. 정상 결과로 사용하지 마세요.",
107삭제: ArchiveError.BudgetExceeded => "입력/해제 크기 또는 처리 시간 한도를 초과했습니다. 더 작은 ZIP으로 시도하세요.",
108삭제: ArchiveError.UnsupportedOperation => "이 ZIP의 암호/압축 방식이나 현재 플랫폼은 개발 검증 해제에서 지원하지 않습니다.",
109삭제: _ => "새 결과 폴더의 안전한 게시를 확인하지 못했습니다. 기존 목록과 선택을 유지했습니다."
110삭제: };
111삭제: }
112삭제: }
삭제src/Zipelo.Desktop/ZipWorkerWorkspace.cs+0-71
@@ -1,71 +0,0 @@
1삭제: using System.IO;
2삭제: using Zipelo.Core;
3삭제: using Zipelo.Runtime;
4삭제:
5삭제: namespace Zipelo.Desktop;
6삭제:
7삭제: internal static class ZipWorkerWorkspace
8삭제: {
9삭제: public static IArchiveWorkspace? TryCreate(out string unavailableReason)
10삭제: {
11삭제: // 사용자 입력이나 압축파일에서 실행 경로를 얻지 않음.
12삭제: unavailableReason = "";
13삭제: var workerDirectory = Path.Combine(AppContext.BaseDirectory, "worker");
14삭제: if (!HasRequiredFiles(workerDirectory))
15삭제: {
16삭제: unavailableReason = "작업에 필요한 프로그램 파일이 누락되었습니다. Zipelo 폴더 전체를 복원한 뒤 다시 실행하세요.";
17삭제: return null;
18삭제: }
19삭제: var workerPath = Path.Combine(workerDirectory, "Zipelo.Worker.exe");
20삭제: var client = new ZipWorkerClient(workerPath);
21삭제: if (!client.IsAvailable)
22삭제: {
23삭제: unavailableReason = WorkspaceMessages.Error(ArchiveError.EngineUnavailable);
24삭제: return null;
25삭제: }
26삭제:
27삭제: var capabilities = client.Capabilities.Where(capability =>
28삭제: capability.Format.Equals("zip", StringComparison.OrdinalIgnoreCase) &&
29삭제: capability.Action == ArchiveAction.List).ToArray();
30삭제: var listing = new CoreWorkspace(async (request, progress, passwords, token) =>
31삭제: {
32삭제: if (request.Action != WorkspaceAction.List || request.Sources.Count != 1 ||
33삭제: !request.Format.Equals("zip", StringComparison.OrdinalIgnoreCase) ||
34삭제: Path.GetExtension(request.Sources[0]).Equals(".jar", StringComparison.OrdinalIgnoreCase))
35삭제: {
36삭제: throw new ArchiveException(ArchiveError.UnsupportedOperation);
37삭제: }
38삭제:
39삭제: if (!HasRequiredFiles(workerDirectory))
40삭제: {
41삭제: throw new ArchiveException(ArchiveError.EngineUnavailable);
42삭제: }
43삭제:
44삭제: // 파싱은 작업자에서 수행함. Desktop은 읽기 전용 스트림만 전달함.
45삭제: await using var input = new FileStream(request.Sources[0], FileMode.Open, FileAccess.Read,
46삭제: FileShare.Read, 65536, FileOptions.Asynchronous | FileOptions.SequentialScan);
47삭제: var limits = new JobLimits(1024, 16L * 1024 * 1024, 16L * 1024 * 1024,
48삭제: TimeSpan.FromMinutes(2), 3);
49삭제: var result = await client.ListAsync(request.JobId, input, limits, token).ConfigureAwait(false);
50삭제: // 런타임은 현재 실시간 진행과 암호 요청을 제공하지 않음. 가짜 이벤트를 만들지 않음.
51삭제: return result.Job;
52삭제: }, capabilities,
53삭제: "단일 ZIP 목록을 지원합니다. 일반 사용자용 생성과 압축 풀기는 검증 전입니다.");
54삭제: return new CreationWorkspace(listing, client, () => HasRequiredFiles(workerDirectory));
55삭제: }
56삭제:
57삭제: private static bool HasRequiredFiles(string directory)
58삭제: {
59삭제: string[] required =
60삭제: [
61삭제: "Zipelo.Worker.exe",
62삭제: "Zipelo.Worker.dll",
63삭제: "Zipelo.Worker.runtimeconfig.json",
64삭제: "Zipelo.Worker.deps.json",
65삭제: "Zipelo.Core.dll",
66삭제: "Zipelo.Runtime.dll"
67삭제: ];
68삭제: return required.All(name => File.Exists(Path.Combine(directory, name)));
69삭제: }
70삭제:
71삭제: }
삭제src/Zipelo.Desktop/Zipelo.Desktop.csproj+0-28
@@ -1,28 +0,0 @@
1삭제: <Project Sdk="Microsoft.NET.Sdk">
2삭제: <PropertyGroup>
3삭제: <OutputType>WinExe</OutputType>
4삭제: <TargetFramework>net10.0-windows</TargetFramework>
5삭제: <UseWPF>true</UseWPF>
6삭제: <EnableWindowsTargeting>true</EnableWindowsTargeting>
7삭제: <Nullable>enable</Nullable>
8삭제: <ImplicitUsings>enable</ImplicitUsings>
9삭제: <ApplicationManifest>app.manifest</ApplicationManifest>
10삭제: <AssemblyName>Zipelo</AssemblyName>
11삭제: <RootNamespace>Zipelo.Desktop</RootNamespace>
12삭제: </PropertyGroup>
13삭제: <PropertyGroup Condition="'$(ZipeloCreationValidation)' == 'true'">
14삭제: <DefineConstants>$(DefineConstants);ZIPELO_CREATION_VALIDATION</DefineConstants>
15삭제: </PropertyGroup>
16삭제: <PropertyGroup Condition="'$(ZipeloExtractionValidation)' == 'true'">
17삭제: <DefineConstants>$(DefineConstants);ZIPELO_EXTRACTION_VALIDATION</DefineConstants>
18삭제: </PropertyGroup>
19삭제: <ItemGroup>
20삭제: <ProjectReference Include="../Zipelo.Core/Zipelo.Core.csproj" />
21삭제: <ProjectReference Include="../Zipelo.Runtime/Zipelo.Runtime.csproj" />
22삭제: <ProjectReference Include="../Zipelo.Worker/Zipelo.Worker.csproj"
23삭제: ReferenceOutputAssembly="false" Private="false"
24삭제: GlobalPropertiesToRemove="PublishProfile;PublishProfileFullPath;PublishDir;OutputPath;OutDir;BaseOutputPath;BaseIntermediateOutputPath;IntermediateOutputPath;TargetDir"
25삭제: AdditionalProperties="UseAppHost=true" />
26삭제: </ItemGroup>
27삭제: <Import Project="WorkerDeployment.targets" />
28삭제: </Project>
삭제src/Zipelo.Desktop/app.manifest+0-16
@@ -1,16 +0,0 @@
1삭제: <?xml version="1.0" encoding="utf-8"?>
2삭제: <assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
3삭제: <assemblyIdentity version="0.1.0.0" name="Zipelo.Desktop" />
4삭제: <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
5삭제: <security>
6삭제: <requestedPrivileges>
7삭제: <requestedExecutionLevel level="asInvoker" uiAccess="false" />
8삭제: </requestedPrivileges>
9삭제: </security>
10삭제: </trustInfo>
11삭제: <application xmlns="urn:schemas-microsoft-com:asm.v3">
12삭제: <windowsSettings>
13삭제: <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
14삭제: </windowsSettings>
15삭제: </application>
16삭제: </assembly>
삭제src/Zipelo.Runtime/LinuxFolderPublication.cs+0-301
@@ -1,301 +0,0 @@
1삭제: using System.Globalization;
2삭제: using System.Runtime.InteropServices;
3삭제: using System.Text;
4삭제: using Microsoft.Win32.SafeHandles;
5삭제: using Zipelo.Core;
6삭제:
7삭제: namespace Zipelo.Runtime;
8삭제:
9삭제: internal sealed class LinuxFolderPublication : PendingFolderPublication
10삭제: {
11삭제: private readonly SafeFileHandle parent;
12삭제: private readonly string parentPath;
13삭제: private ulong parentMountId;
14삭제: private readonly uint user = GetEffectiveUser();
15삭제: private string parentIdentity = "";
16삭제: private bool unboundCreation;
17삭제: internal int? NativeError { get; private set; }
18삭제: internal int? CleanupError { get; private set; }
19삭제:
20삭제: internal LinuxFolderPublication(string path)
21삭제: {
22삭제: parentPath = path;
23삭제: parent = Open(-100, path, 0x90000, 0, 0x04);
24삭제: }
25삭제:
26삭제: internal override void Initialize()
27삭제: {
28삭제: RequireFileSystem();
29삭제: parentIdentity = Inspect(parent, true);
30삭제: AddRoot(Create(parent, TemporaryName, true));
31삭제: }
32삭제:
33삭제: private void RequireFileSystem()
34삭제: {
35삭제: var magic = FileSystemMagic(parent);
36삭제: var expectedType = magic switch
37삭제: {
38삭제: 0xEF53 => "ext4",
39삭제: 0x58465342 => "xfs",
40삭제: _ => throw new ArchiveException(ArchiveError.OutputUnavailable)
41삭제: };
42삭제: var before = MountStatus(parent);
43삭제: var mountId = BitConverter.ToUInt64(before, 144);
44삭제: var device = FormattableString.Invariant($"{BitConverter.ToUInt32(before, 136)}:{BitConverter.ToUInt32(before, 140)}");
45삭제:
46삭제: // procfs 핸들을 고정하고 하위 bind mount와 링크를 통한 정보 대체를 거부함.
47삭제: using var proc = Open(-100, "/proc", 0x90000, 0, 0x04);
48삭제: if (FileSystemMagic(proc) != 0x9FA0) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
49삭제: var name = FormattableString.Invariant($"{GetProcessId()}/task/{GetThreadId()}/mountinfo");
50삭제: using var info = Open(proc.DangerousGetHandle().ToInt32(), name, 0x80000, 0, 0x0F);
51삭제: if (FileSystemMagic(info) != 0x9FA0) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
52삭제: using var stream = new FileStream(info, FileAccess.Read);
53삭제: using var bytes = new MemoryStream();
54삭제: var buffer = new byte[8192];
55삭제: int count;
56삭제: while ((count = stream.Read(buffer, 0, buffer.Length)) != 0)
57삭제: {
58삭제: if (bytes.Length + count > 4 * 1024 * 1024) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
59삭제: bytes.Write(buffer, 0, count);
60삭제: }
61삭제: var content = new UTF8Encoding(false, true).GetString(bytes.ToArray());
62삭제: var matches = 0;
63삭제: foreach (var line in content.Split('\n', StringSplitOptions.RemoveEmptyEntries))
64삭제: {
65삭제: var fields = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
66삭제: if (!ulong.TryParse(fields[0], NumberStyles.None, CultureInfo.InvariantCulture, out var id))
67삭제: {
68삭제: throw new ArchiveException(ArchiveError.OutputUnavailable);
69삭제: }
70삭제: if (id != mountId) { continue; }
71삭제: var separator = Array.IndexOf(fields, "-");
72삭제: if (++matches != 1 || separator < 6 || fields.Length != separator + 4 ||
73삭제: fields[2] != device || fields[separator + 1] != expectedType)
74삭제: {
75삭제: throw new ArchiveException(ArchiveError.OutputUnavailable);
76삭제: }
77삭제: }
78삭제: var after = MountStatus(parent);
79삭제: if (matches != 1 || BitConverter.ToUInt64(after, 144) != mountId ||
80삭제: Identity(before) != Identity(after) || FileSystemMagic(parent) != magic)
81삭제: {
82삭제: throw new ArchiveException(ArchiveError.OutputUnavailable);
83삭제: }
84삭제: parentMountId = mountId;
85삭제: }
86삭제:
87삭제: private byte[] MountStatus(SafeFileHandle handle)
88삭제: {
89삭제: // mountinfo의 기존 mount ID와 대조하므로 UNIQUE 플래그를 요청하지 않음.
90삭제: var status = Stat(handle, "", 0x1100, 0x17FF);
91삭제: if ((BitConverter.ToUInt32(status, 0) & 0x1000) == 0 || BitConverter.ToUInt64(status, 144) == 0)
92삭제: {
93삭제: throw new ArchiveException(ArchiveError.OutputUnavailable);
94삭제: }
95삭제: return status;
96삭제: }
97삭제:
98삭제: private long FileSystemMagic(SafeFileHandle handle)
99삭제: {
100삭제: var system = new byte[256];
101삭제: if (Fstatfs(handle, system) != 0) { ThrowLast(); }
102삭제: return BitConverter.ToInt64(system, 0);
103삭제: }
104삭제:
105삭제: protected override SafeFileHandle Create(SafeFileHandle directory, string name, bool folder)
106삭제: {
107삭제: if (folder)
108삭제: {
109삭제: // 기존 권한은 변경하지 않고 새 디렉터리를 0700 이하로 생성함.
110삭제: if (Mkdirat(directory, name, 0x1C0) != 0) { ThrowLast(); }
111삭제: unboundCreation = true;
112삭제: var handle = Open(directory.DangerousGetHandle().ToInt32(), name, 0x90000, 0, 0x0F);
113삭제: unboundCreation = false;
114삭제: return handle;
115삭제: }
116삭제: return Open(directory.DangerousGetHandle().ToInt32(), name, 0x800C2, 0x180, 0x0F);
117삭제: }
118삭제:
119삭제: protected override string Inspect(SafeFileHandle handle, bool directory)
120삭제: {
121삭제: var status = Stat(handle, "", 0x1100);
122삭제: var mode = BitConverter.ToUInt16(status, 28);
123삭제: if ((mode & 0xF000) != (directory ? 0x4000 : 0x8000) ||
124삭제: BitConverter.ToUInt32(status, 20) != user || (mode & 0x12) != 0 ||
125삭제: (!directory && BitConverter.ToUInt32(status, 16) != 1))
126삭제: {
127삭제: throw new ArchiveException(ArchiveError.OutputUnavailable);
128삭제: }
129삭제: return Identity(status);
130삭제: }
131삭제:
132삭제: private static string Identity(byte[] status)
133삭제: => $"{BitConverter.ToUInt32(status, 136):X8}:{BitConverter.ToUInt32(status, 140):X8}:{BitConverter.ToUInt64(status, 32):X16}";
134삭제:
135삭제: private byte[] Stat(SafeFileHandle directory, string name, int flags, uint mask = 0x7FF)
136삭제: {
137삭제: var status = new byte[256];
138삭제: if (Statx(directory, name, flags, mask, status) != 0) { ThrowLast(); }
139삭제: if ((BitConverter.ToUInt32(status, 0) & 0x10F) != 0x10F)
140삭제: {
141삭제: throw new ArchiveException(ArchiveError.OutputUnavailable);
142삭제: }
143삭제: return status;
144삭제: }
145삭제:
146삭제: protected override void VerifyChildren(Node node, IReadOnlyCollection<string> names)
147삭제: {
148삭제: using var enumeration = Open(node.Handle.DangerousGetHandle().ToInt32(), ".", 0x90000, 0, 0x0F);
149삭제: var buffer = new byte[65536];
150삭제: var remaining = new HashSet<string>(names, StringComparer.Ordinal);
151삭제: while (true)
152삭제: {
153삭제: var count = Getdents64(217, enumeration, buffer, (uint)buffer.Length);
154삭제: if (count < 0) { ThrowLast(); }
155삭제: if (count == 0) { break; }
156삭제: for (var offset = 0; offset < count;)
157삭제: {
158삭제: if (count - offset < 20) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
159삭제: var size = BitConverter.ToUInt16(buffer, offset + 16);
160삭제: if (size < 20 || size > count - offset) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
161삭제: var end = Array.IndexOf(buffer, (byte)0, offset + 19, size - 19);
162삭제: if (end < 0) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
163삭제: var name = new UTF8Encoding(false, true).GetString(buffer, offset + 19, end - offset - 19);
164삭제: if (name is not ("." or "..") && !remaining.Remove(name)) { throw new ArchiveException(ArchiveError.UnsafePath); }
165삭제: offset += size;
166삭제: }
167삭제: }
168삭제: if (remaining.Count != 0) { throw new ArchiveException(ArchiveError.UnsafePath); }
169삭제: }
170삭제:
171삭제: private void RequireName(Node node)
172삭제: {
173삭제: var container = node.Parent?.Handle ?? parent;
174삭제: if (Inspect(container, true) != (node.Parent?.Identity ?? parentIdentity) ||
175삭제: Identity(Stat(container, node.Name, 0x100)) != node.Identity)
176삭제: {
177삭제: throw new ArchiveException(ArchiveError.UnsafePath);
178삭제: }
179삭제: }
180삭제:
181삭제: private void RequireParentIdentity(SafeFileHandle selectedParent)
182삭제: {
183삭제: var pinned = MountStatus(parent);
184삭제: var selected = MountStatus(selectedParent);
185삭제: if (parentMountId == 0 ||
186삭제: BitConverter.ToUInt64(pinned, 144) != parentMountId ||
187삭제: BitConverter.ToUInt64(selected, 144) != parentMountId ||
188삭제: Identity(pinned) != parentIdentity || Identity(selected) != parentIdentity ||
189삭제: Inspect(parent, true) != parentIdentity || Inspect(selectedParent, true) != parentIdentity ||
190삭제: FileSystemMagic(selectedParent) != FileSystemMagic(parent))
191삭제: {
192삭제: throw new ArchiveException(ArchiveError.UnsafePath);
193삭제: }
194삭제: }
195삭제:
196삭제: internal override void Publish(string leaf, CancellationToken token)
197삭제: {
198삭제: RequireName(Root);
199삭제: foreach (var node in Owned.Where(node => node.Directory))
200삭제: {
201삭제: token.ThrowIfCancellationRequested();
202삭제: if (Fsync(node.Handle) != 0) { ThrowLast(); }
203삭제: }
204삭제: token.ThrowIfCancellationRequested();
205삭제: // 원래 경로를 링크 없이 다시 열어 게시 전 교체를 검사함. rename과 원자적이지 않음.
206삭제: using var selectedParent = Open(-100, parentPath, 0x90000, 0, 0x04);
207삭제: RequireParentIdentity(selectedParent);
208삭제: token.ThrowIfCancellationRequested();
209삭제: // RENAME_NOREPLACE가 없는 커널/FS에서는 대체 경로 없이 실패함.
210삭제: if (Renameat2(parent, TemporaryName, parent, leaf, 1) != 0) { ThrowLast(); }
211삭제: }
212삭제:
213삭제: internal override bool Abort()
214삭제: {
215삭제: var success = !unboundCreation;
216삭제: for (var index = Owned.Count - 1; index >= 0; index--)
217삭제: {
218삭제: var node = Owned[index];
219삭제: try
220삭제: {
221삭제: RequireName(node);
222삭제: if (Unlinkat(node.Parent?.Handle ?? parent, node.Name, node.Directory ? 0x200 : 0) != 0)
223삭제: {
224삭제: CleanupError ??= Marshal.GetLastPInvokeError();
225삭제: success = false;
226삭제: }
227삭제: }
228삭제: catch (PosixPublicationException failure) { success = false; CleanupError ??= failure.NativeError; }
229삭제: catch { success = false; }
230삭제: }
231삭제: return success;
232삭제: }
233삭제:
234삭제: public override void Dispose() { DisposeOwned(); parent.Dispose(); }
235삭제:
236삭제: private SafeFileHandle Open(int directory, string name, ulong flags, ulong mode, ulong resolve)
237삭제: {
238삭제: var how = new OpenHow { Flags = flags, Mode = mode, Resolve = resolve };
239삭제: var descriptor = Openat2(437, directory, name, ref how, 24);
240삭제: if (descriptor < 0) { ThrowLast(); }
241삭제: if (descriptor < 3)
242삭제: {
243삭제: var duplicate = Fcntl((int)descriptor, 1030, 3);
244삭제: var error = Marshal.GetLastPInvokeError();
245삭제: Close((int)descriptor);
246삭제: if (duplicate < 0) { Fail(error); }
247삭제: descriptor = duplicate;
248삭제: }
249삭제: return new SafeFileHandle((nint)descriptor, true);
250삭제: }
251삭제:
252삭제: private void ThrowLast() => Fail(Marshal.GetLastPInvokeError());
253삭제: private void Fail(int error)
254삭제: {
255삭제: NativeError = error;
256삭제: throw new PosixPublicationException(error switch
257삭제: {
258삭제: 17 => ArchiveError.OutputConflict,
259삭제: 40 => ArchiveError.UnsafePath,
260삭제: _ => ArchiveError.OutputUnavailable
261삭제: }, error);
262삭제: }
263삭제:
264삭제: [StructLayout(LayoutKind.Sequential)]
265삭제: private struct OpenHow { internal ulong Flags; internal ulong Mode; internal ulong Resolve; }
266삭제: [DllImport("libc", EntryPoint = "syscall", SetLastError = true)]
267삭제: private static extern long Openat2(long syscall, int directory, [MarshalAs(UnmanagedType.LPUTF8Str)] string name,
268삭제: ref OpenHow how, nuint size);
269삭제: [DllImport("libc", EntryPoint = "syscall", SetLastError = true)]
270삭제: private static extern long Getdents64(long syscall, SafeFileHandle directory, [Out] byte[] buffer, uint size);
271삭제: [DllImport("libc", EntryPoint = "statx", SetLastError = true)]
272삭제: private static extern int Statx(SafeFileHandle directory, [MarshalAs(UnmanagedType.LPUTF8Str)] string name,
273삭제: int flags, uint mask, [Out] byte[] status);
274삭제: [DllImport("libc", EntryPoint = "fstatfs", SetLastError = true)]
275삭제: private static extern int Fstatfs(SafeFileHandle directory, [Out] byte[] status);
276삭제: [DllImport("libc", EntryPoint = "mkdirat", SetLastError = true)]
277삭제: private static extern int Mkdirat(SafeFileHandle directory, [MarshalAs(UnmanagedType.LPUTF8Str)] string name, uint mode);
278삭제: [DllImport("libc", EntryPoint = "renameat2", SetLastError = true)]
279삭제: private static extern int Renameat2(SafeFileHandle sourceDirectory, [MarshalAs(UnmanagedType.LPUTF8Str)] string source,
280삭제: SafeFileHandle targetDirectory, [MarshalAs(UnmanagedType.LPUTF8Str)] string target, uint flags);
281삭제: [DllImport("libc", EntryPoint = "unlinkat", SetLastError = true)]
282삭제: private static extern int Unlinkat(SafeFileHandle directory, [MarshalAs(UnmanagedType.LPUTF8Str)] string name, int flags);
283삭제: [DllImport("libc", EntryPoint = "fsync", SetLastError = true)]
284삭제: private static extern int Fsync(SafeFileHandle file);
285삭제: [DllImport("libc", EntryPoint = "getpid")]
286삭제: private static extern int GetProcessId();
287삭제: [DllImport("libc", EntryPoint = "gettid")]
288삭제: private static extern int GetThreadId();
289삭제: [DllImport("libc", EntryPoint = "geteuid")]
290삭제: private static extern uint GetEffectiveUser();
291삭제: [DllImport("libc", EntryPoint = "fcntl", SetLastError = true)]
292삭제: private static extern int Fcntl(int descriptor, int command, int minimum);
293삭제: [DllImport("libc", EntryPoint = "close")]
294삭제: private static extern int Close(int descriptor);
295삭제: }
296삭제:
297삭제: internal sealed class PosixPublicationException(ArchiveError code, int error) : Exception(code.ToString())
298삭제: {
299삭제: internal ArchiveError Code { get; } = code;
300삭제: internal int NativeError { get; } = error;
301삭제: }
삭제src/Zipelo.Runtime/LinuxPublication.cs+0-98
@@ -1,98 +0,0 @@
1삭제: using System.Runtime.InteropServices;
2삭제: using Microsoft.Win32.SafeHandles;
3삭제: using Zipelo.Core;
4삭제:
5삭제: namespace Zipelo.Runtime;
6삭제:
7삭제: internal sealed class LinuxPublication : PendingPublication
8삭제: {
9삭제: private readonly SafeFileHandle directory;
10삭제: private readonly SafeFileHandle file;
11삭제:
12삭제: private LinuxPublication(SafeFileHandle directory, SafeFileHandle file)
13삭제: {
14삭제: this.directory = directory;
15삭제: this.file = file;
16삭제: }
17삭제:
18삭제: internal override SafeFileHandle Handle => file;
19삭제:
20삭제: internal static LinuxPublication Create(string parent)
21삭제: {
22삭제: // x64 syscall 번호를 사용함. 호출 전 공통 API에서 아키텍처를 제한함.
23삭제: var how = new OpenHow { Flags = 0x80000 | 0x10000, Mode = 0, Resolve = 0x04 };
24삭제: var descriptor = OpenAt2(437, -100, parent, ref how, (nuint)Marshal.SizeOf<OpenHow>());
25삭제: var directory = OwnDescriptor(checked((int)descriptor));
26삭제: try
27삭제: {
28삭제: // O_TMPFILE | O_RDWR | O_CLOEXEC, 생성 권한은 0600 이하임.
29삭제: var file = OwnDescriptor(OpenAt(directory, ".", 0x410000 | 2 | 0x80000, 0x180));
30삭제: return new(directory, file);
31삭제: }
32삭제: catch { directory.Dispose(); throw; }
33삭제: }
34삭제:
35삭제: internal override void Publish(string leaf)
36삭제: {
37삭제: // 커널 procfs의 보유 fd를 연결하며 새 목적지 링크는 덮어쓰지 않음.
38삭제: var descriptorPath = $"/proc/self/fd/{file.DangerousGetHandle().ToInt64()}";
39삭제: if (LinkAt(-100, descriptorPath, directory, leaf, 0x400) != 0) { ThrowLastError(); }
40삭제: }
41삭제:
42삭제: // 이름 없는 임시 inode는 마지막 핸들이 닫힐 때 제거됨.
43삭제: internal override bool Abort() => true;
44삭제:
45삭제: public override void Dispose()
46삭제: {
47삭제: file.Dispose();
48삭제: directory.Dispose();
49삭제: }
50삭제:
51삭제: private static SafeFileHandle OwnDescriptor(int descriptor)
52삭제: {
53삭제: if (descriptor < 0) { ThrowLastError(); }
54삭제: if (descriptor < 3)
55삭제: {
56삭제: var duplicate = DuplicateDescriptor(descriptor, 1030, 3);
57삭제: var error = Marshal.GetLastPInvokeError();
58삭제: Close(descriptor);
59삭제: if (duplicate < 0) { throw Error(error); }
60삭제: descriptor = duplicate;
61삭제: }
62삭제: return new SafeFileHandle((nint)descriptor, ownsHandle: true);
63삭제: }
64삭제:
65삭제: private static void ThrowLastError() => throw Error(Marshal.GetLastPInvokeError());
66삭제: private static ArchiveException Error(int error) => new(error switch
67삭제: {
68삭제: 17 => ArchiveError.OutputConflict,
69삭제: 40 => ArchiveError.UnsafePath,
70삭제: _ => ArchiveError.OutputUnavailable
71삭제: });
72삭제:
73삭제: [StructLayout(LayoutKind.Sequential)]
74삭제: private struct OpenHow
75삭제: {
76삭제: internal ulong Flags;
77삭제: internal ulong Mode;
78삭제: internal ulong Resolve;
79삭제: }
80삭제:
81삭제: [DllImport("libc", EntryPoint = "syscall", SetLastError = true)]
82삭제: private static extern long OpenAt2(long number, int directory,
83삭제: [MarshalAs(UnmanagedType.LPUTF8Str)] string path, ref OpenHow how, nuint size);
84삭제:
85삭제: [DllImport("libc", EntryPoint = "openat", SetLastError = true)]
86삭제: private static extern int OpenAt(SafeFileHandle directory,
87삭제: [MarshalAs(UnmanagedType.LPUTF8Str)] string path, int flags, uint mode);
88삭제:
89삭제: [DllImport("libc", EntryPoint = "linkat", SetLastError = true)]
90삭제: private static extern int LinkAt(int oldDirectory, [MarshalAs(UnmanagedType.LPUTF8Str)] string oldPath,
91삭제: SafeFileHandle newDirectory, [MarshalAs(UnmanagedType.LPUTF8Str)] string newPath, int flags);
92삭제:
93삭제: [DllImport("libc", EntryPoint = "fcntl", SetLastError = true)]
94삭제: private static extern int DuplicateDescriptor(int descriptor, int command, int minimum);
95삭제:
96삭제: [DllImport("libc", EntryPoint = "close")]
97삭제: private static extern int Close(int descriptor);
98삭제: }
삭제src/Zipelo.Runtime/NewFolderPublisher.cs+0-76
@@ -1,76 +0,0 @@
1삭제: using System.Runtime.InteropServices;
2삭제: using Zipelo.Core;
3삭제:
4삭제: namespace Zipelo.Runtime;
5삭제:
6삭제: public static class NewFolderPublisher
7삭제: {
8삭제: // 구현 진입 가능 여부임. 일반 UI 활성화나 OS 검증 완료를 뜻하지 않음.
9삭제: public static bool IsSupportedPlatform => RuntimeInformation.ProcessArchitecture == Architecture.X64 &&
10삭제: (OperatingSystem.IsWindows() || OperatingSystem.IsLinux());
11삭제:
12삭제: public static async Task<ZipPublicationResult> PublishAsync(ZipWorkerResult result,
13삭제: string destinationPath, CancellationToken token)
14삭제: {
15삭제: PendingFolderPublication? pending = null;
16삭제: var published = false;
17삭제: var error = ArchiveError.None;
18삭제: var cleanupFailed = false;
19삭제: int? posixError = null;
20삭제: string? temporaryName = null;
21삭제: PublicationNativeFailure? nativeFailure = null;
22삭제: PublicationNativeFailure? cleanupNativeFailure = null;
23삭제: try
24삭제: {
25삭제: token.ThrowIfCancellationRequested();
26삭제: if (!IsSupportedPlatform) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
27삭제: var entries = ZipExtraction.ValidateResult(result, token, snapshot: true);
28삭제: if (!Path.IsPathFullyQualified(destinationPath)) { throw new ArchiveException(ArchiveError.UnsafePath); }
29삭제: var fullPath = Path.GetFullPath(destinationPath);
30삭제: if (OperatingSystem.IsLinux()) { _ = OutputPathPolicy.Validate(fullPath[1..], FileNamePolicy.Linux); }
31삭제: var parent = Path.GetDirectoryName(fullPath);
32삭제: var leaf = Path.GetFileName(fullPath);
33삭제: if (parent is null || OutputPathPolicy.Validate(leaf, OutputPathPolicy.CurrentPolicy).Count != 1)
34삭제: {
35삭제: throw new ArchiveException(ArchiveError.UnsafePath);
36삭제: }
37삭제: pending = OperatingSystem.IsWindows() ? new WindowsFolderPublication(parent) : new LinuxFolderPublication(parent);
38삭제: pending.Initialize();
39삭제: foreach (var entry in entries) { await pending.WriteAsync(entry, token).ConfigureAwait(false); }
40삭제: pending.Verify(token);
41삭제: token.ThrowIfCancellationRequested();
42삭제: pending.Publish(leaf, token);
43삭제: published = true;
44삭제: }
45삭제: catch (OperationCanceledException) when (token.IsCancellationRequested) { error = ArchiveError.Cancelled; }
46삭제: catch (PublicationNativeException failure) { error = failure.Code; nativeFailure = failure.Failure; }
47삭제: catch (PosixPublicationException failure) { error = failure.Code; posixError = failure.NativeError; }
48삭제: catch (ArchiveException failure) { error = failure.Code; }
49삭제: catch (ArgumentException) { error = ArchiveError.UnsafePath; }
50삭제: catch { error = ArchiveError.OutputUnavailable; }
51삭제: finally
52삭제: {
53삭제: if (pending is not null)
54삭제: {
55삭제: if (!published)
56삭제: {
57삭제: try { cleanupFailed = !pending.Abort(); }
58삭제: catch { cleanupFailed = true; }
59삭제: if (cleanupFailed)
60삭제: {
61삭제: temporaryName = pending.TemporaryName;
62삭제: cleanupNativeFailure = pending.CleanupNativeFailure;
63삭제: }
64삭제: }
65삭제: pending.Dispose();
66삭제: }
67삭제: }
68삭제: return new(published, error, cleanupFailed, temporaryName)
69삭제: {
70삭제: NativeFailure = nativeFailure,
71삭제: CleanupNativeFailure = cleanupNativeFailure,
72삭제: PosixError = posixError,
73삭제: CleanupPosixError = (pending as LinuxFolderPublication)?.CleanupError
74삭제: };
75삭제: }
76삭제: }
삭제src/Zipelo.Runtime/NewZipPublisher.cs+0-123
@@ -1,123 +0,0 @@
1삭제: using System.Runtime.InteropServices;
2삭제: using Microsoft.Win32.SafeHandles;
3삭제: using Zipelo.Core;
4삭제:
5삭제: namespace Zipelo.Runtime;
6삭제:
7삭제: public sealed record ZipPublicationResult(bool Published, ArchiveError Error, bool CleanupFailed,
8삭제: string? TemporaryFileName = null)
9삭제: {
10삭제: public int? PosixError { get; init; }
11삭제: public int? CleanupPosixError { get; init; }
12삭제: public PublicationNativeFailure? NativeFailure { get; init; }
13삭제: public PublicationNativeFailure? CleanupNativeFailure { get; init; }
14삭제: }
15삭제:
16삭제: // 경로와 OS 오류 메시지 없이 고정 API 이름과 숫자 코드만 전달함.
17삭제: public sealed record PublicationNativeFailure(string Operation, uint Win32Error, int? NtStatus = null);
18삭제:
19삭제: internal sealed class PublicationNativeException(ArchiveError code, PublicationNativeFailure failure)
20삭제: : Exception(code.ToString())
21삭제: {
22삭제: internal ArchiveError Code { get; } = code;
23삭제: internal PublicationNativeFailure Failure { get; } = failure;
24삭제: }
25삭제:
26삭제: public static class NewZipPublisher
27삭제: {
28삭제: // 구현 대상 여부임. OS별 실행 검증 완료나 대상 파일시스템 지원을 뜻하지 않음.
29삭제: public static bool IsSupportedPlatform => RuntimeInformation.ProcessArchitecture == Architecture.X64 &&
30삭제: (OperatingSystem.IsWindows() || OperatingSystem.IsLinux());
31삭제:
32삭제: public static async Task<ZipPublicationResult> PublishAsync(ZipWorkerResult result,
33삭제: string destinationPath, CancellationToken token)
34삭제: {
35삭제: PendingPublication? pending = null;
36삭제: var published = false;
37삭제: var error = ArchiveError.None;
38삭제: var cleanupFailed = false;
39삭제: string? temporaryFileName = null;
40삭제: PublicationNativeFailure? nativeFailure = null;
41삭제: PublicationNativeFailure? cleanupNativeFailure = null;
42삭제: try
43삭제: {
44삭제: token.ThrowIfCancellationRequested();
45삭제: if (!IsSupportedPlatform) { throw new ArchiveException(ArchiveError.OutputUnavailable); }
46삭제: var bytes = result.CreatedZip;
47삭제: if (result.Job.State != JobState.Completed || result.Job.Error != ArchiveError.None ||
48삭제: bytes is null || bytes.Length == 0)
49삭제: {
50삭제: throw new ArchiveException(ArchiveError.UnsupportedOperation);
51삭제: }
52삭제: if (bytes.Length > WorkerProtocol.MaxDataBytes) { throw new ArchiveException(ArchiveError.BudgetExceeded); }
53삭제: if (!Path.IsPathFullyQualified(destinationPath)) { throw new ArchiveException(ArchiveError.UnsafePath); }
54삭제: var fullPath = Path.GetFullPath(destinationPath);
55삭제: if (OperatingSystem.IsLinux())
56삭제: {
57삭제: _ = OutputPathPolicy.Validate(fullPath[1..], FileNamePolicy.Linux);
58삭제: }
59삭제: var parent = Path.GetDirectoryName(fullPath);
60삭제: var leaf = Path.GetFileName(fullPath);
61삭제: if (parent is null || OutputPathPolicy.Validate(leaf, OutputPathPolicy.CurrentPolicy).Count != 1)
62삭제: {
63삭제: throw new ArchiveException(ArchiveError.UnsafePath);
64삭제: }
65삭제: // 호출자가 생성물 배열을 이후 변경해도 쓰는 내용이 달라지지 않도록 복사함.
66삭제: var snapshot = bytes.ToArray();
67삭제: pending = OperatingSystem.IsWindows() ? WindowsPublication.Create(parent) : LinuxPublication.Create(parent);
68삭제: for (var offset = 0; offset < snapshot.Length; offset += 65536)
69삭제: {
70삭제: token.ThrowIfCancellationRequested();
71삭제: var count = Math.Min(65536, snapshot.Length - offset);
72삭제: await RandomAccess.WriteAsync(pending.Handle, snapshot.AsMemory(offset, count), offset, token)
73삭제: .ConfigureAwait(false);
74삭제: }
75삭제: RandomAccess.FlushToDisk(pending.Handle);
76삭제: token.ThrowIfCancellationRequested();
77삭제: pending.Publish(leaf);
78삭제: // 게시 성공 이후의 늦은 취소는 이미 존재하는 새 파일을 취소 결과로 바꾸지 않음.
79삭제: published = true;
80삭제: }
81삭제: catch (OperationCanceledException) when (token.IsCancellationRequested) { error = ArchiveError.Cancelled; }
82삭제: catch (PublicationNativeException failure)
83삭제: {
84삭제: error = failure.Code;
85삭제: nativeFailure = failure.Failure;
86삭제: }
87삭제: catch (ArchiveException failure) { error = failure.Code; }
88삭제: catch (ArgumentException) { error = ArchiveError.UnsafePath; }
89삭제: catch { error = ArchiveError.OutputUnavailable; }
90삭제: finally
91삭제: {
92삭제: if (pending is not null)
93삭제: {
94삭제: if (!published)
95삭제: {
96삭제: try { cleanupFailed = !pending.Abort(); }
97삭제: catch { cleanupFailed = true; }
98삭제: if (cleanupFailed)
99삭제: {
100삭제: temporaryFileName = pending.TemporaryFileName;
101삭제: cleanupNativeFailure = pending.CleanupNativeFailure;
102삭제: }
103삭제: }
104삭제: pending.Dispose();
105삭제: }
106삭제: }
107삭제: return new(published, error, cleanupFailed, temporaryFileName)
108삭제: {
109삭제: NativeFailure = nativeFailure,
110삭제: CleanupNativeFailure = cleanupNativeFailure
111삭제: };
112삭제: }
113삭제: }
114삭제:
115삭제: internal abstract class PendingPublication : IDisposable
116삭제: {
117삭제: internal abstract SafeFileHandle Handle { get; }
118삭제: internal virtual string? TemporaryFileName => null;
119삭제: internal virtual PublicationNativeFailure? CleanupNativeFailure => null;
120삭제: internal abstract void Publish(string leaf);
121삭제: internal abstract bool Abort();
122삭제: public abstract void Dispose();
123삭제: }
삭제src/Zipelo.Runtime/PendingFolderPublication.cs+0-100
@@ -1,100 +0,0 @@
1삭제: using Microsoft.Win32.SafeHandles;
2삭제: using Zipelo.Core;
3삭제:
4삭제: namespace Zipelo.Runtime;
5삭제:
6삭제: internal abstract class PendingFolderPublication : IDisposable
7삭제: {
8삭제: protected sealed class Node(string name, Node? parent, SafeFileHandle handle, bool directory, string identity)
9삭제: {
10삭제: internal string Name { get; } = name;
11삭제: internal Node? Parent { get; } = parent;
12삭제: internal SafeFileHandle Handle { get; set; } = handle;
13삭제: internal bool Directory { get; } = directory;
14삭제: internal string Identity { get; } = identity;
15삭제: }
16삭제:
17삭제: protected readonly List<Node> Owned = [];
18삭제: private readonly Dictionary<string, Node> folders = new(OutputPathPolicy.Comparer(OutputPathPolicy.CurrentPolicy));
19삭제: internal string TemporaryName { get; } = $".zipelo-{Guid.NewGuid():N}.tmp";
20삭제: internal PublicationNativeFailure? CleanupNativeFailure { get; set; }
21삭제: protected Node Root => Owned[0];
22삭제: protected abstract SafeFileHandle Create(SafeFileHandle parent, string name, bool directory);
23삭제: protected abstract string Inspect(SafeFileHandle handle, bool directory);
24삭제: protected abstract void VerifyChildren(Node node, IReadOnlyCollection<string> names);
25삭제: internal abstract void Initialize();
26삭제: internal abstract void Publish(string leaf, CancellationToken token);
27삭제: internal abstract bool Abort();
28삭제: public abstract void Dispose();
29삭제:
30삭제: protected void AddRoot(SafeFileHandle handle)
31삭제: {
32삭제: // 검사 실패도 호출자의 Abort가 생성 핸들을 정리하도록 먼저 기록함.
33삭제: var root = new Node(TemporaryName, null, handle, true, "");
34삭제: Owned.Add(root);
35삭제: var verified = new Node(TemporaryName, null, handle, true, Inspect(handle, true));
36삭제: Owned[0] = verified;
37삭제: folders.Add("", verified);
38삭제: }
39삭제:
40삭제: internal async Task WriteAsync(ZipExtractedEntry item, CancellationToken token)
41삭제: {
42삭제: var segments = OutputPathPolicy.Validate(item.Entry.Name, OutputPathPolicy.CurrentPolicy);
43삭제: var parent = Root;
44삭제: for (var index = 0; index < segments.Count; index++)
45삭제: {
46삭제: token.ThrowIfCancellationRequested();
47삭제: var path = string.Join('/', segments.Take(index + 1));
48삭제: var directory = index < segments.Count - 1 || item.Entry.Kind == EntryKind.Directory;
49삭제: if (directory && folders.TryGetValue(path, out var existing)) { parent = existing; continue; }
50삭제: var handle = Create(parent.Handle, segments[index], directory);
51삭제: var node = new Node(segments[index], parent, handle, directory, "");
52삭제: Owned.Add(node);
53삭제: node = new Node(node.Name, parent, handle, directory, Inspect(handle, directory));
54삭제: Owned[^1] = node;
55삭제: if (directory)
56삭제: {
57삭제: folders.Add(path, node);
58삭제: parent = node;
59삭제: continue;
60삭제: }
61삭제: var buffer = new byte[65536];
62삭제: for (var offset = 0; offset < item.Content.Length; offset += buffer.Length)
63삭제: {
64삭제: token.ThrowIfCancellationRequested();
65삭제: var count = Math.Min(buffer.Length, item.Content.Length - offset);
66삭제: await RandomAccess.WriteAsync(handle, item.Content.AsMemory(offset, count), offset, token).ConfigureAwait(false);
67삭제: }
68삭제: RandomAccess.FlushToDisk(handle);
69삭제: if (RandomAccess.GetLength(handle) != item.Content.Length) { throw new ArchiveException(ArchiveError.IntegrityFailure); }
70삭제: for (var offset = 0; offset < item.Content.Length;)
71삭제: {
72삭제: var count = await RandomAccess.ReadAsync(handle, buffer.AsMemory(0,
73삭제: Math.Min(buffer.Length, item.Content.Length - offset)), offset, token).ConfigureAwait(false);
74삭제: if (count == 0 || !buffer.AsSpan(0, count).SequenceEqual(item.Content.AsSpan(offset, count)))
75삭제: {
76삭제: throw new ArchiveException(ArchiveError.IntegrityFailure);
77삭제: }
78삭제: offset += count;
79삭제: }
80삭제: }
81삭제: }
82삭제:
83삭제: internal void Verify(CancellationToken token)
84삭제: {
85삭제: foreach (var node in Owned)
86삭제: {
87삭제: token.ThrowIfCancellationRequested();
88삭제: if (Inspect(node.Handle, node.Directory) != node.Identity) { throw new ArchiveException(ArchiveError.UnsafePath); }
89삭제: if (node.Directory)
90삭제: {
91삭제: VerifyChildren(node, Owned.Where(child => child.Parent == node).Select(child => child.Name).ToArray());
92삭제: }
93삭제: }
94삭제: }
95삭제:
96삭제: protected void DisposeOwned()
97삭제: {
98삭제: for (var index = Owned.Count - 1; index >= 0; index--) { Owned[index].Handle.Dispose(); }
99삭제: }
100삭제: }
삭제src/Zipelo.Runtime/Streaming/WorkerStreamChannel.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Runtime/Streaming/WorkerStreamContract.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Runtime/Streaming/WorkerStreamValidator.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Runtime/WindowsFolderGuard.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Runtime/WindowsFolderPublication.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Runtime/WindowsPublication.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Runtime/WorkerPlatform.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Runtime/WorkerProtocol.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Runtime/ZipExtraction.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Runtime/ZipWorkerClient.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Runtime/Zipelo.Runtime.csproj

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Ubuntu/App.axaml

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Ubuntu/App.axaml.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Ubuntu/MainWindow.axaml

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Ubuntu/MainWindow.axaml.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Ubuntu/Program.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Ubuntu/Properties/PublishProfiles/LinuxX64.pubxml

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Ubuntu/UbuntuWorkspace.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Ubuntu/WorkerDeployment.targets

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Ubuntu/Zipelo.Ubuntu.csproj

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Worker/BoundedMemoryOutput.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Worker/BuiltInZipEngine.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Worker/Program.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Worker/Tar/UstarReader.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Worker/ZipExtractor.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제src/Zipelo.Worker/Zipelo.Worker.csproj

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/frontend/check_desktop.py

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/gzip-boundary-probe/Program.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/gzip-history-integration-probe/BoundaryProbe.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/gzip-history-integration-probe/BudgetRegression.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/gzip-history-integration-probe/FinalizationRegression.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/gzip-history-integration-probe/IntegrationProgram.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/gzip-history-integration-probe/PendingValidation.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/gzip-history-integration-probe/contract.json

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/run_checks.py

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/runtime/ExtractionPublicationTests.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/runtime/ExtractionTests.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/runtime/FolderConcurrencyTests.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/runtime/FolderEnvironment.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/runtime/Program.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/runtime/ProtocolPeer.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/runtime/PublicationTests.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/runtime/RuntimeTests.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/runtime/TestWorkerLaunch.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/runtime/Zipelo.RuntimeTests.csproj

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/security/.gitignore

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/security/CoreRegressions.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/security/CoreTests.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/security/NuGet.Config

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/security/PlatformRegressions.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/security/Program.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/security/TestSupport.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/security/Zipelo.SecurityTests.csproj

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/security/check_fixtures.py

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/security/check_runner.py

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/security/coverage.json

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/security/fixture_factory.py

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/security/fixtures/backslash-traversal.zip

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
삭제tests/security/fixtures/bad-crc.zip

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
삭제tests/security/fixtures/case-collision.zip

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
삭제tests/security/fixtures/normal.zip

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
삭제tests/security/fixtures/parent-collision.zip

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
삭제tests/security/fixtures/symlink.zip

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
삭제tests/security/fixtures/traversal.zip

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
삭제tests/security/fixtures/truncated.zip

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
삭제tests/security/platform_matrix.json

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/stream-protocol/ChannelTests.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/stream-protocol/ControlledStream.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/stream-protocol/NuGet.Config

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/stream-protocol/Program.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/stream-protocol/TestSupport.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/stream-protocol/ValidatorTests.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/stream-protocol/Zipelo.StreamProtocolTests.csproj

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/stream-protocol/contract.json

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/tar-stream-reader/Program.cs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/tar-stream-reader/Zipelo.TarReaderTests.csproj

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
삭제tests/tar-stream-reader/contract.json

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기