team-ljyzipelo

공개
263줄12 KB
1using System.Globalization;
2using System.Security.Cryptography;
3using System.Text;
4using Zipelo.Core;
5
6namespace Zipelo.Worker.Tar;
7
8internal sealed record UstarLimits(JobLimits Job, long MaxInputBytes, long MaxMetadataBytes);
9internal sealed record UstarResult(IReadOnlyList<ArchiveEntry> Entries, BudgetUsage Usage,
10 string InputSha256, VerificationState ContentVerification);
11
12// 수신기는 청크를 복사하거나 즉시 소비함. 성공 반환 전에는 게시하지 않으며 실패 시 전부 폐기함.
13internal delegate ValueTask UstarSink(ArchiveEntry entry, ReadOnlyMemory<byte> bytes, CancellationToken token);
14
15// 입력은 호출자가 독점 보유한 seek 가능 스트림임. 입력과 수신기를 닫지 않음.
16internal sealed class UstarReader
17{
18 internal const int ChunkSize = 64 * 1024;
19 internal const long InputCap = 16 * 1024 * 1024;
20 internal const long MetadataCap = 1024 * 1024;
21 private const int BlockSize = 512;
22 private static readonly UTF8Encoding Utf8 = new(false, true);
23 private readonly JobBudget budget;
24 private readonly long inputLimit;
25 private readonly long metadataLimit;
26 private readonly FileNamePolicy policy;
27 private int used;
28
29 internal UstarReader(UstarLimits limits, FileNamePolicy policy, TimeProvider? time = null)
30 {
31 ArgumentNullException.ThrowIfNull(limits);
32 ArgumentNullException.ThrowIfNull(limits.Job);
33 if (limits.MaxInputBytes <= 0 || limits.MaxMetadataBytes <= 0)
34 {
35 throw new ArgumentOutOfRangeException(nameof(limits));
36 }
37 _ = OutputPathPolicy.Comparer(policy);
38 this.policy = policy;
39 inputLimit = Math.Min(limits.MaxInputBytes, InputCap);
40 metadataLimit = Math.Min(limits.MaxMetadataBytes, MetadataCap);
41 budget = new JobBudget(limits.Job with
42 {
43 MaxEntries = Math.Min(limits.Job.MaxEntries, 1024),
44 MaxProcessedBytes = Math.Min(limits.Job.MaxProcessedBytes, 128L * 1024 * 1024),
45 MaxOutputBytes = Math.Min(limits.Job.MaxOutputBytes, 16L * 1024 * 1024),
46 MaxDuration = limits.Job.MaxDuration < TimeSpan.FromMinutes(5)
47 ? limits.Job.MaxDuration : TimeSpan.FromMinutes(5)
48 }, time);
49 }
50
51 // 선택은 검증 완료된 목록의 순번 ID로 고정함. 빈 선택은 목록만 반환함.
52 internal async Task<UstarResult> ReadAsync(Stream input,
53 Func<IReadOnlyList<ArchiveEntry>, IReadOnlyCollection<string>> select,
54 UstarSink sink, CancellationToken token)
55 {
56 ArgumentNullException.ThrowIfNull(input);
57 ArgumentNullException.ThrowIfNull(select);
58 ArgumentNullException.ThrowIfNull(sink);
59 if (Interlocked.Exchange(ref used, 1) != 0) { throw new InvalidOperationException(); }
60 budget.Check(token);
61 if (!input.CanRead || !input.CanSeek) { throw new ArgumentException("Seekable input required.", nameof(input)); }
62 var length = input.Length;
63 if (length > inputLimit) { throw new ArchiveException(ArchiveError.BudgetExceeded); }
64 if (length < 1024 || length % BlockSize != 0) { Fail(); }
65
66 var entries = new List<ArchiveEntry>();
67 var first = await ScanAsync(input, length, entries, null, sink, token).ConfigureAwait(false);
68 var inventory = entries.AsReadOnly();
69 budget.Check(token);
70 var requested = select(inventory) ?? throw new ArgumentException("Selection required.", nameof(select));
71 budget.Check(token);
72 if (requested.Count > entries.Count) { throw new ArchiveException(ArchiveError.UnsupportedEntry); }
73 var selected = new HashSet<string>(StringComparer.Ordinal);
74 foreach (var id in requested)
75 {
76 budget.Check(token);
77 if (selected.Count >= entries.Count || !selected.Add(id) || !entries.Any(e => e.Id == id))
78 {
79 throw new ArchiveException(ArchiveError.UnsupportedEntry);
80 }
81 }
82 if (selected.Count != 0)
83 {
84 var second = await ScanAsync(input, length, entries, selected, sink, token).ConfigureAwait(false);
85 if (!CryptographicOperations.FixedTimeEquals(first, second)) { Fail(); }
86 }
87 budget.Check(token);
88 // SHA256은 두 순회 입력의 동일성 확인용임. TAR에는 본문 무결성 값이 없음.
89 return new UstarResult(inventory, budget.Usage, Convert.ToHexString(first), VerificationState.Unavailable);
90 }
91
92 private async Task<byte[]> ScanAsync(Stream input, long length, List<ArchiveEntry> entries,
93 HashSet<string>? selected, UstarSink sink, CancellationToken token)
94 {
95 if (input.Length != length) { Fail(); }
96 input.Position = 0;
97 using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
98 var buffer = new byte[ChunkSize];
99 var header = new byte[BlockSize];
100 var seen = new Dictionary<string, EntryKind>(OutputPathPolicy.Comparer(policy));
101 long consumed = 0;
102 long metadata = 0;
103 var index = 0;
104 while (true)
105 {
106 await ReadExactAsync(header).ConfigureAwait(false);
107 if (IsZero(header))
108 {
109 await ReadExactAsync(header).ConfigureAwait(false);
110 if (!IsZero(header)) { Fail(); }
111 while (consumed < length)
112 {
113 var count = (int)Math.Min(buffer.Length, length - consumed);
114 await ReadExactAsync(buffer.AsMemory(0, count)).ConfigureAwait(false);
115 if (!IsZero(buffer.AsSpan(0, count))) { Fail(); }
116 }
117 break;
118 }
119 if (selected is null) { budget.AddEntry(token); }
120 if (metadataLimit - metadata < BlockSize) { throw new ArchiveException(ArchiveError.BudgetExceeded); }
121 metadata += BlockSize;
122 var entry = ParseHeader(header, index);
123 RequireUnique(entry, seen);
124 if (selected is null) { entries.Add(entry); }
125 else if (index >= entries.Count || entries[index] != entry) { Fail(); }
126 index++;
127 var size = entry.DeclaredSize!.Value;
128 var padding = (BlockSize - size % BlockSize) % BlockSize;
129 // 감산 비교로 거대한 선언값의 덧셈 오버플로를 피함.
130 if (size > length - consumed || padding > length - consumed - size) { Fail(); }
131 var emit = selected?.Contains(entry.Id) == true && entry.Kind == EntryKind.File;
132 if (emit) { budget.ReserveOutput(size, token); }
133 if (emit && size == 0) { await sink(entry, ReadOnlyMemory<byte>.Empty, token).ConfigureAwait(false); }
134 for (long remaining = size; remaining > 0;)
135 {
136 var count = (int)Math.Min(ChunkSize, remaining);
137 await ReadExactAsync(buffer.AsMemory(0, count)).ConfigureAwait(false);
138 if (emit) { await sink(entry, buffer.AsMemory(0, count), token).ConfigureAwait(false); }
139 budget.Check(token);
140 remaining -= count;
141 }
142 if (padding > 0)
143 {
144 await ReadExactAsync(buffer.AsMemory(0, (int)padding)).ConfigureAwait(false);
145 if (!IsZero(buffer.AsSpan(0, (int)padding))) { Fail(); }
146 }
147 }
148 budget.Check(token);
149 if (input.Length != length || input.Position != length || (selected is not null && index != entries.Count)) { Fail(); }
150 return hash.GetHashAndReset();
151
152 async ValueTask ReadExactAsync(Memory<byte> destination)
153 {
154 if (destination.Length > length - consumed) { Fail(); }
155 while (!destination.IsEmpty)
156 {
157 budget.Check(token);
158 var read = await input.ReadAsync(destination, token).ConfigureAwait(false);
159 if (read <= 0 || read > destination.Length) { Fail(); }
160 budget.ChargeProcessed(read, token);
161 hash.AppendData(destination.Span[..read]);
162 consumed += read;
163 destination = destination[read..];
164 }
165 }
166 }
167
168 private ArchiveEntry ParseHeader(byte[] header, int index)
169 {
170 var h = header.AsSpan();
171 var stored = Octal(h.Slice(148, 8));
172 long sum = 0;
173 for (var i = 0; i < BlockSize; i++) { sum += i is >= 148 and < 156 ? 32 : h[i]; }
174 if (stored != sum) { Fail(); }
175 if (!h.Slice(257, 6).SequenceEqual("ustar\0"u8) || !h.Slice(263, 2).SequenceEqual("00"u8))
176 {
177 throw new ArchiveException(ArchiveError.UnsupportedEntry);
178 }
179 var kind = h[156] switch
180 {
181 0 or (byte)'0' => EntryKind.File,
182 (byte)'5' => EntryKind.Directory,
183 _ => throw new ArchiveException(ArchiveError.UnsupportedEntry)
184 };
185 _ = Octal(h.Slice(100, 8));
186 _ = Octal(h.Slice(108, 8));
187 _ = Octal(h.Slice(116, 8));
188 var size = Octal(h.Slice(124, 12));
189 _ = Octal(h.Slice(136, 12));
190 if (Octal(h.Slice(329, 8), true) != 0 || Octal(h.Slice(337, 8), true) != 0 ||
191 !IsZero(h.Slice(157, 100)) || !IsZero(h.Slice(500, 12))) { Fail(); }
192 _ = Text(h.Slice(265, 32));
193 _ = Text(h.Slice(297, 32));
194 var name = Text(h[..100]);
195 var prefix = Text(h.Slice(345, 155));
196 if (name.Length == 0) { Fail(); }
197 if (prefix.Length > 0) { name = prefix + "/" + name; }
198 if (kind == EntryKind.Directory && name.EndsWith('/')) { name = name[..^1]; }
199 if (kind == EntryKind.Directory && size != 0) { Fail(); }
200 if (name.Contains('\\')) { throw new ArchiveException(ArchiveError.UnsafePath); }
201 name = string.Join("/", OutputPathPolicy.Validate(name, policy));
202 return new ArchiveEntry(index.ToString(CultureInfo.InvariantCulture), name, kind, size);
203 }
204
205 private void RequireUnique(ArchiveEntry entry, Dictionary<string, EntryKind> seen)
206 {
207 if (seen.ContainsKey(entry.Name)) { throw new ArchiveException(ArchiveError.OutputConflict); }
208 foreach (var previous in seen)
209 {
210 if ((previous.Value == EntryKind.File && IsDescendant(entry.Name, previous.Key)) ||
211 (entry.Kind == EntryKind.File && IsDescendant(previous.Key, entry.Name)))
212 {
213 throw new ArchiveException(ArchiveError.OutputConflict);
214 }
215 }
216 seen.Add(entry.Name, entry.Kind);
217 }
218
219 private bool IsDescendant(string path, string ancestor) =>
220 path.Length > ancestor.Length && path[ancestor.Length] == '/' &&
221 path.AsSpan(0, ancestor.Length).Equals(ancestor.AsSpan(), OutputPathPolicy.Comparison(policy));
222
223 private static string Text(ReadOnlySpan<byte> field)
224 {
225 var end = field.IndexOf((byte)0);
226 if (end >= 0)
227 {
228 if (!IsZero(field[end..])) { Fail(); }
229 field = field[..end];
230 }
231 try { return Utf8.GetString(field); }
232 catch (DecoderFallbackException) { throw new ArchiveException(ArchiveError.IntegrityFailure); }
233 }
234
235 private static long Octal(ReadOnlySpan<byte> field, bool allowEmpty = false)
236 {
237 long value = 0;
238 var digits = 0;
239 var ended = false;
240 foreach (var b in field)
241 {
242 if (b is 0 or 32)
243 {
244 if (digits > 0 || b == 0) { ended = true; }
245 continue;
246 }
247 if (ended || b < (byte)'0' || b > (byte)'7') { Fail(); }
248 if (value > (long.MaxValue - (b - (byte)'0')) / 8) { Fail(); }
249 value = value * 8 + b - (byte)'0';
250 digits++;
251 }
252 if (digits == 0 && !allowEmpty) { Fail(); }
253 return value;
254 }
255
256 private static bool IsZero(ReadOnlySpan<byte> bytes)
257 {
258 foreach (var b in bytes) { if (b != 0) { return false; } }
259 return true;
260 }
261
262 private static void Fail() => throw new ArchiveException(ArchiveError.IntegrityFailure);
263}