team-ljyzipelo

공개
106줄5.1 KB
1using System.IO.Compression;
2using Zipelo.Core;
3using Zipelo.Runtime;
4
5namespace Zipelo.Worker;
6
7// 압축 파싱은 작업자에서만 수행함. UI에서 이 구현을 직접 참조하지 않음.
8internal sealed class BuiltInZipEngine(string[] names, long outputLimit) : IArchiveEngine
9{
10 public IReadOnlyCollection<EngineCapability> Capabilities { get; } = Array.AsReadOnly(new[]
11 {
12 new EngineCapability("zip", ArchiveAction.List),
13 new EngineCapability("zip", ArchiveAction.Create)
14 });
15
16 public async Task ExecuteAsync(ArchiveAction action, IReadOnlyList<Stream> inputs,
17 EngineContext context, CancellationToken token)
18 {
19 try
20 {
21 if (action == ArchiveAction.List)
22 {
23 if (inputs.Count != 1) { throw new ArchiveException(ArchiveError.UnsupportedOperation); }
24 context.Budget.ChargeProcessed(inputs[0].Length, token);
25 using var archive = new ZipArchive(inputs[0], ZipArchiveMode.Read, leaveOpen: true);
26 if (archive.Entries.Count > WorkerProtocol.MaxEntries)
27 {
28 throw new ArchiveException(ArchiveError.BudgetExceeded);
29 }
30 for (var index = 0; index < archive.Entries.Count; index++)
31 {
32 context.Budget.Check(token);
33 var entry = archive.Entries[index];
34 if (entry.FullName.Length > WorkerProtocol.MaxNameLength)
35 {
36 throw new ArchiveException(ArchiveError.BudgetExceeded);
37 }
38 if (entry.IsEncrypted) { throw new ArchiveException(ArchiveError.UnsupportedOperation); }
39 var unixType = (entry.ExternalAttributes >> 16) & 0xF000;
40 var kind = unixType == 0xA000 ? EntryKind.SymbolicLink :
41 entry.FullName.EndsWith('/') || unixType == 0x4000 ? EntryKind.Directory :
42 unixType is 0 or 0x8000 ? EntryKind.File : EntryKind.Other;
43 // 목록은 내용의 CRC나 경로 안전성을 검증한 결과가 아님.
44 await context.ListEntryAsync(new($"entry-{index}", entry.FullName, kind, entry.Length))
45 .ConfigureAwait(false);
46 }
47 return;
48 }
49 if (action != ArchiveAction.Create || inputs.Count != names.Length)
50 {
51 throw new ArchiveException(ArchiveError.UnsupportedOperation);
52 }
53
54 var normalized = ValidateNames(names);
55 using var zip = new BoundedMemoryStream(Math.Min(outputLimit, WorkerProtocol.MaxDataBytes));
56 using (var archive = new ZipArchive(zip, ZipArchiveMode.Create, leaveOpen: true))
57 {
58 var buffer = new byte[64 * 1024];
59 for (var index = 0; index < inputs.Count; index++)
60 {
61 context.Budget.Check(token);
62 await context.ListEntryAsync(new($"source-{index}", normalized[index], EntryKind.File, inputs[index].Length))
63 .ConfigureAwait(false);
64 var entry = archive.CreateEntry(normalized[index], CompressionLevel.Optimal);
65 await using var destination = entry.Open();
66 int count;
67 while ((count = await inputs[index].ReadAsync(buffer, token).ConfigureAwait(false)) != 0)
68 {
69 context.Budget.ChargeProcessed(count, token);
70 await destination.WriteAsync(buffer.AsMemory(0, count), token).ConfigureAwait(false);
71 }
72 }
73 }
74 context.Budget.Check(token);
75 zip.Position = 0;
76 await context.WriteEntryAsync(new("artifact", "archive.zip", EntryKind.File, zip.Length), zip,
77 _ => ValueTask.FromResult(VerificationState.NotChecked)).ConfigureAwait(false);
78 }
79 catch (InvalidDataException) { throw new ArchiveException(ArchiveError.IntegrityFailure); }
80 }
81
82 private static string[] ValidateNames(string[] names)
83 {
84 var normalized = new string[names.Length];
85 var policy = OutputPathPolicy.CurrentPolicy;
86 var comparison = OutputPathPolicy.Comparison(policy);
87 var seen = new HashSet<string>(OutputPathPolicy.Comparer(policy));
88 for (var index = 0; index < names.Length; index++)
89 {
90 if (names[index].Length > WorkerProtocol.MaxNameLength)
91 {
92 throw new ArchiveException(ArchiveError.BudgetExceeded);
93 }
94 var name = string.Join('/', OutputPathPolicy.Validate(names[index], policy));
95 if (seen.Any(existing => existing.Equals(name, comparison) ||
96 existing.StartsWith(name + "/", comparison) ||
97 name.StartsWith(existing + "/", comparison)))
98 {
99 throw new ArchiveException(ArchiveError.OutputConflict);
100 }
101 seen.Add(name);
102 normalized[index] = name;
103 }
104 return normalized;
105 }
106}