team-ljyzipelo

공개
424줄19 KB
1using System.Buffers.Binary;
2using System.IO.Compression;
3using System.Security.Cryptography;
4using System.Text;
5using ICSharpCode.SharpZipLib.Zip.Compression;
6using Zipelo.GzipBoundaryProbe;
7
8internal static class Program
9{
10 private static int passed;
11 private static int failed;
12
13 public static int Main(string[] args)
14 {
15 if (args.Length != 0) { return 2; }
16 Run("crc.known-vector", () => Equal(Fixture.Crc("123456789"u8), 0xcbf43926U));
17 var text = "123456789"u8.ToArray();
18 var large = Enumerable.Range(0, 200003).Select(i => (byte)(i * 17)).ToArray();
19 foreach (var data in new[] { Array.Empty<byte>(), text, large })
20 {
21 var fixture = Fixture.Create(data);
22 foreach (var feed in new[] { 1, 2, 3, 7, 8, 9, 31, 512, 65536 })
23 {
24 Run($"valid.{data.Length}.{feed}", () => Verify(fixture, data, feed));
25 }
26 Run($"unselected.{data.Length}", () =>
27 {
28 var budget = new ProbeBudget(new(Output: 0));
29 var result = BoundaryProbe.Read(fixture.Bytes, budget, false,
30 _ => throw new Exception("선택하지 않은 바이트가 전달됨"));
31 Equal(result.InflatedBytes, (long)data.Length);
32 Equal(budget.Output, 0L);
33 Equal(budget.Processed, (long)fixture.Bytes.Length + data.Length);
34 });
35 }
36 foreach (byte flags in Enumerable.Range(0, 32).Select(i => (byte)i))
37 {
38 var fixture = Fixture.Create(text, flags);
39 Run($"header.flags.{flags}", () => Verify(fixture, text, 1));
40 }
41 foreach (var length in new[] { 65520, 65521, 65535, 65536, 65537, 131073 })
42 {
43 var data = large[..length];
44 var stored = Fixture.Create(data, level: CompressionLevel.NoCompression);
45 Run($"boundary.stored-chunks.{length}", () => Verify(stored, data, 65536));
46 }
47 var basic = Fixture.Create(text);
48 Run("boundary.readahead", () =>
49 {
50 var result = Verify(basic, text, 65536);
51 Equal(result.ReadAheadBytes, 8);
52 Equal(result.OfferedBytes, (long)basic.RawLength + 8);
53 });
54 Run("boundary.byte-feed", () =>
55 {
56 var result = Verify(basic, text, 1);
57 Check(result.ReadAheadBytes <= 1);
58 });
59 foreach (var raw in new[] { new byte[] { 3, 0 }, new byte[] { 1, 0, 0, 255, 255 } })
60 {
61 var fixture = Fixture.Wrap(raw, [], 0);
62 Run($"empty.raw.{raw.Length}", () => Verify(fixture, [], 1));
63 }
64 Run("empty.fixture.raw-boundary-hash", () =>
65 {
66 var fixture = Fixture.Create([]);
67 Equal(fixture.RawLength, 2);
68 Check(fixture.Bytes.AsSpan(fixture.HeaderLength, fixture.RawLength)
69 .SequenceEqual(new byte[] { 0x03, 0x00 }));
70 Verify(fixture, [], 1);
71 Verify(fixture, [], 65536);
72 });
73 Run("raw.finished-consumed-unread", RawContract);
74 Run("crc.known-trailer", () =>
75 {
76 var trailer = BinaryPrimitives.ReadUInt32LittleEndian(basic.Bytes.AsSpan(basic.Bytes.Length - 8));
77 Equal(trailer, 0xcbf43926U);
78 });
79 foreach (var offset in new[] { 0, 1, 2 })
80 {
81 Run($"header.invalid.{offset}", () => Reject(Mutate(basic.Bytes, offset), Failure.Header));
82 }
83 foreach (var bit in new[] { 0x20, 0x40, 0x80 })
84 {
85 Run($"header.reserved.{bit}", () => Reject(Mutate(basic.Bytes, 3, (byte)bit), Failure.Header));
86 }
87 for (var i = 0; i < 4; i++)
88 {
89 var offset = basic.Bytes.Length - 8 + i;
90 Run($"crc.byte.{i}", () => Reject(Mutate(basic.Bytes, offset), Failure.Crc));
91 offset += 4;
92 var sizeOffset = offset;
93 Run($"isize.byte.{i}", () => Reject(Mutate(basic.Bytes, sizeOffset), Failure.Size));
94 }
95 var optional = Fixture.Create(text, 31);
96 Run("header.fhcrc", () => Reject(Mutate(optional.Bytes, optional.HeaderLength - 2), Failure.Header));
97 Run("header.fhcrc-covers-name", () => Reject(Mutate(optional.Bytes, 18), Failure.Header));
98 Run("header.fname-no-path-use", () => Verify(Fixture.Create(text, 8, "../../escape"), text, 7));
99 Run("header.unterminated-name", () => Reject([31, 139, 8, 8, 0, 0, 0, 0, 0, 255, 65], Failure.Truncated));
100 Run("header.unterminated-comment", () => Reject([31, 139, 8, 16, 0, 0, 0, 0, 0, 255, 65], Failure.Truncated));
101 Run("header.extra-truncated", () => Reject([31, 139, 8, 4, 0, 0, 0, 0, 0, 255, 255, 255, 1], Failure.Truncated));
102 Run("deflate.invalid-block", () => Reject(Fixture.Wrap([7], [], 0).Bytes, Failure.Deflate));
103 Run("deflate.invalid-backreference-history", () =>
104 Reject(Fixture.Wrap([0x03, 0x02, 0x00], [0, 0, 0], 0).Bytes, Failure.Deflate));
105 Run("deflate.valid-three-zero-bytes", () => Verify(Fixture.Create([0, 0, 0]), [0, 0, 0], 65536));
106 foreach (var suffix in new[] { new byte[] { 0 }, new byte[] { 255 }, new byte[512], basic.Bytes,
107 Fixture.Create([]).Bytes, new byte[] { 31, 139 } })
108 {
109 Run($"trailing.{suffix.Length}.{suffix[0]}", () => Reject([.. basic.Bytes, .. suffix], Failure.TrailingData));
110 }
111 for (var length = 0; length < optional.Bytes.Length; length++)
112 {
113 var prefix = optional.Bytes[..length];
114 Run($"truncate.{length}", () => RejectAny(prefix));
115 }
116 Run("sink.pending-after-crc-failure", () =>
117 {
118 using var sink = new HashSink();
119 Expect(Failure.Crc, () => BoundaryProbe.Read(Mutate(basic.Bytes, basic.Bytes.Length - 8),
120 new(new()), true, sink.Append));
121 Equal(sink.Bytes, (long)text.Length);
122 Check(sink.CommittedHash == null);
123 });
124 Run("unselected.bad-crc", () => Reject(Mutate(basic.Bytes, basic.Bytes.Length - 8), Failure.Crc, selected: false));
125 Run("unselected.trailing", () => Reject([.. basic.Bytes, 0], Failure.TrailingData, selected: false));
126 Run("budget.input", () => Reject(basic.Bytes, Failure.Budget, new(Input: basic.Bytes.Length - 1)));
127 Run("budget.processed", () => Reject(basic.Bytes, Failure.Budget,
128 new(Processed: basic.Bytes.Length + text.Length - 1)));
129 Run("budget.output", () => Reject(basic.Bytes, Failure.Budget, new(Output: text.Length - 1)));
130 Run("budget.metadata", () => Reject(optional.Bytes, Failure.Budget, new(Metadata: optional.HeaderLength - 1)));
131 Run("budget.exact", () => Verify(optional, text, 65536,
132 new(Input: optional.Bytes.Length, Processed: optional.Bytes.Length + text.Length,
133 Output: text.Length, Metadata: optional.HeaderLength)));
134 Run("budget.metadata-cap", () => Reject(Fixture.Create([], 8, new string('a', 1024 * 1024)).Bytes,
135 Failure.Budget, new(Metadata: long.MaxValue)));
136 Run("budget.input-cap", () => Reject(new byte[16 * 1024 * 1024 + 1], Failure.Budget, new(Input: long.MaxValue)));
137 Run("budget.clamps", () =>
138 {
139 var budget = new ProbeBudget(new(long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue, TimeSpan.MaxValue));
140 Equal(budget.InputLimit, 16777216L);
141 Equal(budget.ProcessedLimit, 134217728L);
142 Equal(budget.OutputLimit, 16777216L);
143 Equal(budget.MetadataLimit, 1048576L);
144 Equal(budget.Duration, TimeSpan.FromMinutes(5));
145 });
146 Run("budget.cumulative-processed", () =>
147 {
148 var budget = new ProbeBudget(new(Processed: 2L * (basic.Bytes.Length + text.Length) - 1));
149 using var first = new HashSink();
150 first.Complete(BoundaryProbe.Read(basic.Bytes, budget, true, first.Append));
151 using var second = new HashSink();
152 Expect(Failure.Budget, () => BoundaryProbe.Read(basic.Bytes, budget, true, second.Append));
153 Check(first.CommittedHash != null && second.CommittedHash == null);
154 });
155 Run("budget.cumulative-output", () =>
156 {
157 var budget = new ProbeBudget(new(Output: text.Length));
158 BoundaryProbe.Read(basic.Bytes, budget, true, _ => { });
159 Expect(Failure.Budget, () => BoundaryProbe.Read(basic.Bytes, budget, true, _ => { }));
160 });
161 Run("budget.cumulative-metadata", () =>
162 {
163 var budget = new ProbeBudget(new(Metadata: basic.HeaderLength));
164 BoundaryProbe.Read(basic.Bytes, budget, false, _ => { });
165 Expect(Failure.Budget, () => BoundaryProbe.Read(basic.Bytes, budget, false, _ => { }));
166 });
167 Run("budget.unselected-expansion", () => Reject(Fixture.Create(large).Bytes, Failure.Budget,
168 new(Processed: 10000), selected: false));
169 Run("budget.deadline", () =>
170 {
171 var clock = new ManualClock();
172 var budget = new ProbeBudget(new(Duration: TimeSpan.FromSeconds(1)), clock);
173 clock.Advance(TimeSpan.FromSeconds(1));
174 Expect(Failure.Budget, () => BoundaryProbe.Read(basic.Bytes, budget, false, _ => { }));
175 });
176 Run("budget.sink-time", () =>
177 {
178 var clock = new ManualClock();
179 var budget = new ProbeBudget(new(Duration: TimeSpan.FromSeconds(1)), clock);
180 Expect(Failure.Budget, () => BoundaryProbe.Read(basic.Bytes, budget, true,
181 _ => clock.Advance(TimeSpan.FromSeconds(1))));
182 });
183 Run("cancel.before", () =>
184 {
185 using var cts = new CancellationTokenSource();
186 cts.Cancel();
187 ExpectCanceled(() => BoundaryProbe.Read(basic.Bytes, new(new()), true, _ => { }, cts.Token));
188 });
189 Run("cancel.sink", () =>
190 {
191 using var cts = new CancellationTokenSource();
192 using var sink = new HashSink();
193 ExpectCanceled(() => BoundaryProbe.Read(basic.Bytes, new(new()), true,
194 bytes => { sink.Append(bytes); cts.Cancel(); }, cts.Token));
195 Check(sink.Bytes > 0 && sink.CommittedHash == null);
196 });
197 Run("cancel.unselected-inflater", () =>
198 {
199 using var cts = new CancellationTokenSource();
200 ExpectCanceled(() => BoundaryProbe.Read(basic.Bytes, new(new()), false, _ => { }, cts.Token,
201 inflater: new CancelInflater(cts)));
202 });
203 Run("sink.exception", () =>
204 {
205 var sentinel = new InvalidOperationException("시험 수신기 실패");
206 try { BoundaryProbe.Read(basic.Bytes, new(new()), true, _ => throw sentinel); }
207 catch (InvalidOperationException error) when (ReferenceEquals(error, sentinel)) { return; }
208 throw new Exception("수신기 예외가 보존되지 않음");
209 });
210 Run("inflater.no-progress", () => Expect(Failure.NoProgress, () =>
211 BoundaryProbe.Read(basic.Bytes, new(new()), true, _ => { }, inflater: new StalledInflater())));
212 Run("inflater.contract-violation", () => Expect(Failure.Boundary, () =>
213 BoundaryProbe.Read(basic.Bytes, new(new()), true, _ => { }, inflater: new BrokenInflater())));
214 Console.WriteLine($"passed={passed} failed={failed}");
215 return failed == 0 ? 0 : 1;
216 }
217
218 private static BoundaryResult Verify(Fixture fixture, byte[] plain, int feed, Limits? limits = null)
219 {
220 using var sink = new HashSink();
221 var budget = new ProbeBudget(limits ?? new());
222 var result = BoundaryProbe.Read(fixture.Bytes, budget, true, sink.Append, feedSize: feed);
223 Check(sink.CommittedHash == null);
224 sink.Complete(result);
225 Equal(sink.CommittedHash!, Convert.ToHexString(SHA256.HashData(plain)));
226 Equal(result.HeaderBytes, fixture.HeaderLength);
227 Equal(result.DeflateBytes, (long)fixture.RawLength);
228 Equal(result.InflatedBytes, (long)plain.Length);
229 Equal(result.InflaterTotalOut, (long)plain.Length);
230 Equal(result.MemberBytes, fixture.Bytes.Length);
231 Equal(result.OfferedBytes - result.ReadAheadBytes, result.DeflateBytes);
232 Equal(budget.Processed, (long)fixture.Bytes.Length + plain.Length);
233 Equal(budget.Metadata, (long)fixture.HeaderLength);
234 Equal(budget.Output, (long)plain.Length);
235 Check(sink.MaxChunk <= ProbeBudget.ChunkSize);
236 return result;
237 }
238
239 private static void RawContract()
240 {
241 var data = Enumerable.Repeat((byte)65, 16384).ToArray();
242 var fixture = Fixture.Create(data);
243 var raw = fixture.Bytes.AsSpan(fixture.HeaderLength, fixture.RawLength).ToArray();
244 byte[] input = [.. raw, 11, 22, 33, 44, 55, 66, 77, 88];
245 var inflater = new Inflater(true);
246 inflater.SetInput(input);
247 var output = new byte[1];
248 var count = 0;
249 var pendingObserved = false;
250 while (!inflater.IsFinished)
251 {
252 Check(count <= data.Length);
253 var before = inflater.TotalIn;
254 var n = inflater.Inflate(output);
255 Check(n == 1 || inflater.IsFinished || inflater.TotalIn > before);
256 if (n == 1) { Equal(output[0], (byte)65); count++; }
257 Equal(inflater.TotalIn + inflater.RemainingInput, (long)input.Length);
258 if (count < data.Length && inflater.RemainingInput >= 8) { pendingObserved |= !inflater.IsFinished; }
259 }
260 Equal(count, data.Length);
261 Equal(inflater.TotalIn, (long)raw.Length);
262 Equal(inflater.RemainingInput, 8);
263 Equal(inflater.TotalOut, (long)data.Length);
264 Check(pendingObserved);
265 Check(input.AsSpan(input.Length - inflater.RemainingInput).SequenceEqual(new byte[] { 11, 22, 33, 44, 55, 66, 77, 88 }));
266 }
267
268 private static void Reject(byte[] input, Failure failure, Limits? limits = null, bool selected = true)
269 {
270 using var sink = new HashSink();
271 Expect(failure, () => BoundaryProbe.Read(input, new(limits ?? new()), selected, sink.Append));
272 Check(sink.CommittedHash == null);
273 }
274
275 private static void RejectAny(byte[] input)
276 {
277 using var sink = new HashSink();
278 try { BoundaryProbe.Read(input, new(new()), true, sink.Append, feedSize: 1); }
279 catch (ProbeException error) when (error.Failure is Failure.Header or Failure.Truncated or Failure.Deflate or Failure.Crc or Failure.Size)
280 {
281 Check(sink.CommittedHash == null);
282 return;
283 }
284 throw new Exception("잘린 입력이 거부되지 않음");
285 }
286
287 private static byte[] Mutate(byte[] input, int offset, byte mask = 1)
288 {
289 var copy = (byte[])input.Clone();
290 copy[offset] ^= mask;
291 return copy;
292 }
293
294 private static void Expect(Failure failure, Action action)
295 {
296 try { action(); }
297 catch (ProbeException error) when (error.Failure == failure) { return; }
298 throw new Exception($"예상 실패 없음: {failure}");
299 }
300
301 private static void ExpectCanceled(Action action)
302 {
303 try { action(); }
304 catch (OperationCanceledException) { return; }
305 throw new Exception("취소가 전파되지 않음");
306 }
307
308 private static void Run(string name, Action action)
309 {
310 try { action(); passed++; Console.WriteLine($"PASS {name}"); }
311 catch (Exception error) { failed++; Console.WriteLine($"FAIL {name}: {error.GetType().Name}: {error.Message}"); }
312 }
313
314 private static void Check(bool value)
315 {
316 if (!value) { throw new Exception("검사 실패"); }
317 }
318
319 private static void Equal<T>(T actual, T expected) where T : notnull => Check(EqualityComparer<T>.Default.Equals(actual, expected));
320}
321
322internal sealed class HashSink : IDisposable
323{
324 private readonly IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
325 public long Bytes { get; private set; }
326 public int MaxChunk { get; private set; }
327 public string? CommittedHash { get; private set; }
328
329 public void Append(ReadOnlyMemory<byte> bytes)
330 {
331 if (CommittedHash != null || bytes.Length > ProbeBudget.ChunkSize) { throw new InvalidOperationException(); }
332 hash.AppendData(bytes.Span);
333 Bytes += bytes.Length;
334 MaxChunk = Math.Max(MaxChunk, bytes.Length);
335 }
336
337 public void Complete(BoundaryResult result)
338 {
339 if (Bytes != result.InflatedBytes || CommittedHash != null) { throw new InvalidOperationException(); }
340 CommittedHash = Convert.ToHexString(hash.GetHashAndReset());
341 }
342
343 public void Dispose() => hash.Dispose();
344}
345
346internal sealed record Fixture(byte[] Bytes, int HeaderLength, int RawLength)
347{
348 public static Fixture Create(byte[] plain, byte flags = 0, string name = "sample.txt",
349 CompressionLevel level = CompressionLevel.Optimal)
350 {
351 if (plain.Length == 0)
352 {
353 return Wrap([0x03, 0x00], plain, flags, name);
354 }
355 using var raw = new MemoryStream();
356 using (var compressor = new DeflateStream(raw, level, true)) { compressor.Write(plain); }
357 return Wrap(raw.ToArray(), plain, flags, name);
358 }
359
360 public static Fixture Wrap(byte[] raw, byte[] plain, byte flags, string name = "sample.txt")
361 {
362 using var output = new MemoryStream();
363 output.Write(new byte[] { 31, 139, 8, flags, 0, 0, 0, 0, 0, 255 });
364 if ((flags & 4) != 0) { output.Write(new byte[] { 4, 0, 11, 22, 33, 44 }); }
365 if ((flags & 8) != 0) { output.Write(Encoding.Latin1.GetBytes(name)); output.WriteByte(0); }
366 if ((flags & 16) != 0) { output.Write("comment"u8); output.WriteByte(0); }
367 if ((flags & 2) != 0)
368 {
369 var crc = Crc(output.ToArray());
370 output.WriteByte((byte)crc);
371 output.WriteByte((byte)(crc >> 8));
372 }
373 var header = (int)output.Length;
374 output.Write(raw);
375 Span<byte> trailer = stackalloc byte[8];
376 BinaryPrimitives.WriteUInt32LittleEndian(trailer, Crc(plain));
377 BinaryPrimitives.WriteUInt32LittleEndian(trailer[4..], (uint)plain.Length);
378 output.Write(trailer);
379 return new(output.ToArray(), header, raw.Length);
380 }
381
382 // 시험 기대값은 라이브러리 CRC 구현과 독립적으로 계산함.
383 public static uint Crc(ReadOnlySpan<byte> bytes)
384 {
385 var crc = uint.MaxValue;
386 foreach (var value in bytes)
387 {
388 crc ^= value;
389 for (var bit = 0; bit < 8; bit++) { crc = (crc >> 1) ^ ((crc & 1) == 0 ? 0U : 0xedb88320U); }
390 }
391 return ~crc;
392 }
393}
394
395internal sealed class ManualClock : TimeProvider
396{
397 private long ticks;
398 public override long TimestampFrequency => TimeSpan.TicksPerSecond;
399 public override long GetTimestamp() => ticks;
400 public void Advance(TimeSpan duration) => ticks += duration.Ticks;
401}
402
403internal class StalledInflater : IRawInflater
404{
405 protected int supplied;
406 public bool IsFinished => false;
407 public bool IsNeedingInput => supplied == 0;
408 public bool IsNeedingDictionary => false;
409 public virtual long TotalIn => 0;
410 public long TotalOut => 0;
411 public int RemainingInput => supplied;
412 public void SetInput(byte[] bytes, int count) => supplied += count;
413 public virtual int Inflate(byte[] output) => 0;
414}
415
416internal sealed class BrokenInflater : StalledInflater
417{
418 public override long TotalIn => supplied == 0 ? 0 : supplied + 1L;
419}
420
421internal sealed class CancelInflater(CancellationTokenSource cts) : StalledInflater
422{
423 public override int Inflate(byte[] output) { cts.Cancel(); return 0; }
424}