| 1 | using System.Buffers.Binary; |
| 2 | using ICSharpCode.SharpZipLib; |
| 3 | using ICSharpCode.SharpZipLib.Checksum; |
| 4 | using ICSharpCode.SharpZipLib.Zip.Compression; |
| 5 | |
| 6 | namespace Zipelo.GzipBoundaryProbe; |
| 7 | |
| 8 | internal enum Failure |
| 9 | { |
| 10 | Header, Truncated, Deflate, Boundary, Crc, Size, TrailingData, Budget, NoProgress |
| 11 | } |
| 12 | |
| 13 | internal sealed class ProbeException(Failure failure) : Exception(failure.ToString()) |
| 14 | { |
| 15 | public Failure Failure { get; } = failure; |
| 16 | } |
| 17 | |
| 18 | internal sealed record Limits( |
| 19 | long Input = 16L * 1024 * 1024, |
| 20 | long Processed = 128L * 1024 * 1024, |
| 21 | long Output = 16L * 1024 * 1024, |
| 22 | long Metadata = 1024 * 1024, |
| 23 | TimeSpan? Duration = null); |
| 24 | |
| 25 | // 여러 순회의 처리량과 선택 출력, 메타데이터 및 시간을 누적함. |
| 26 | internal sealed class ProbeBudget |
| 27 | { |
| 28 | public const int ChunkSize = 65536; |
| 29 | public long InputLimit { get; } |
| 30 | public long ProcessedLimit { get; } |
| 31 | public long OutputLimit { get; } |
| 32 | public long MetadataLimit { get; } |
| 33 | public TimeSpan Duration { get; } |
| 34 | public long Processed { get; private set; } |
| 35 | public long Output { get; private set; } |
| 36 | public long Metadata { get; private set; } |
| 37 | private readonly TimeProvider clock; |
| 38 | private readonly long started; |
| 39 | |
| 40 | public ProbeBudget(Limits limits, TimeProvider? clock = null) |
| 41 | { |
| 42 | if (limits.Input < 0 || limits.Processed < 0 || limits.Output < 0 || limits.Metadata < 0 || |
| 43 | limits.Duration is { } duration && duration <= TimeSpan.Zero) |
| 44 | { |
| 45 | throw new ArgumentOutOfRangeException(nameof(limits)); |
| 46 | } |
| 47 | InputLimit = Math.Min(limits.Input, 16L * 1024 * 1024); |
| 48 | ProcessedLimit = Math.Min(limits.Processed, 128L * 1024 * 1024); |
| 49 | OutputLimit = Math.Min(limits.Output, 16L * 1024 * 1024); |
| 50 | MetadataLimit = Math.Min(limits.Metadata, 1024 * 1024); |
| 51 | Duration = limits.Duration is { } requested && requested < TimeSpan.FromMinutes(5) |
| 52 | ? requested : TimeSpan.FromMinutes(5); |
| 53 | this.clock = clock ?? TimeProvider.System; |
| 54 | started = this.clock.GetTimestamp(); |
| 55 | } |
| 56 | |
| 57 | public void Check(CancellationToken token) |
| 58 | { |
| 59 | token.ThrowIfCancellationRequested(); |
| 60 | if (Processed > ProcessedLimit || clock.GetElapsedTime(started) >= Duration) { throw new ProbeException(Failure.Budget); } |
| 61 | } |
| 62 | |
| 63 | public void ChargeProcessed(int count) |
| 64 | { |
| 65 | if (count < 0 || count > ProcessedLimit - Processed) { throw new ProbeException(Failure.Budget); } |
| 66 | Processed += count; |
| 67 | } |
| 68 | |
| 69 | // 이미 생성된 출력은 한도 초과 시에도 기록하며 이후 호출을 차단함. |
| 70 | public void ChargeDecoded(int count) |
| 71 | { |
| 72 | if (count < 0 || count > ChunkSize) { throw new ProbeException(Failure.Boundary); } |
| 73 | if (Processed > ProcessedLimit) { throw new ProbeException(Failure.Budget); } |
| 74 | Processed += count; |
| 75 | if (Processed > ProcessedLimit) { throw new ProbeException(Failure.Budget); } |
| 76 | } |
| 77 | |
| 78 | public void ChargeOutput(int count) |
| 79 | { |
| 80 | if (count < 0 || count > OutputLimit - Output) { throw new ProbeException(Failure.Budget); } |
| 81 | Output += count; |
| 82 | } |
| 83 | |
| 84 | public void ChargeMetadata() |
| 85 | { |
| 86 | if (Metadata >= MetadataLimit) { throw new ProbeException(Failure.Budget); } |
| 87 | Metadata++; |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | // 시험용 어댑터이며 생산 코드에서 참조하지 않음. |
| 92 | internal interface IRawInflater |
| 93 | { |
| 94 | bool IsFinished { get; } |
| 95 | bool IsNeedingInput { get; } |
| 96 | bool IsNeedingDictionary { get; } |
| 97 | long TotalIn { get; } |
| 98 | long TotalOut { get; } |
| 99 | int RemainingInput { get; } |
| 100 | void SetInput(byte[] bytes, int count); |
| 101 | int Inflate(byte[] output); |
| 102 | } |
| 103 | |
| 104 | internal sealed class SharpInflater : IRawInflater |
| 105 | { |
| 106 | private readonly Inflater inflater = new(true); |
| 107 | public bool IsFinished => inflater.IsFinished; |
| 108 | public bool IsNeedingInput => inflater.IsNeedingInput; |
| 109 | public bool IsNeedingDictionary => inflater.IsNeedingDictionary; |
| 110 | public long TotalIn => inflater.TotalIn; |
| 111 | public long TotalOut => inflater.TotalOut; |
| 112 | public int RemainingInput => inflater.RemainingInput; |
| 113 | public void SetInput(byte[] bytes, int count) => inflater.SetInput(bytes, 0, count); |
| 114 | public int Inflate(byte[] output) => inflater.Inflate(output, 0, output.Length); |
| 115 | } |
| 116 | |
| 117 | internal sealed record BoundaryResult( |
| 118 | int HeaderBytes, long DeflateBytes, int ReadAheadBytes, long InflatedBytes, |
| 119 | uint Crc32, int MemberBytes, long OfferedBytes, long InflaterTotalOut); |
| 120 | |
| 121 | internal static class BoundaryProbe |
| 122 | { |
| 123 | // 입력 메모리는 호출 동안 불변이어야 함. 수신 청크는 성공 반환 전까지 임시 결과임. |
| 124 | public static BoundaryResult Read(ReadOnlyMemory<byte> input, ProbeBudget budget, |
| 125 | bool selected, Action<ReadOnlyMemory<byte>> sink, CancellationToken token = default, |
| 126 | int feedSize = ProbeBudget.ChunkSize, IRawInflater? inflater = null) |
| 127 | { |
| 128 | ArgumentNullException.ThrowIfNull(budget); |
| 129 | ArgumentNullException.ThrowIfNull(sink); |
| 130 | if (feedSize is < 1 or > ProbeBudget.ChunkSize) { throw new ArgumentOutOfRangeException(nameof(feedSize)); } |
| 131 | budget.Check(token); |
| 132 | if (input.Length > budget.InputLimit) { throw new ProbeException(Failure.Budget); } |
| 133 | var cursor = new Cursor(input, budget, token); |
| 134 | var headerCrc = new Crc32(); |
| 135 | byte HeaderByte() |
| 136 | { |
| 137 | budget.Check(token); |
| 138 | budget.ChargeMetadata(); |
| 139 | var value = cursor.Byte(); |
| 140 | headerCrc.Update(value); |
| 141 | return value; |
| 142 | } |
| 143 | if (HeaderByte() != 0x1f || HeaderByte() != 0x8b || HeaderByte() != 8) |
| 144 | { |
| 145 | throw new ProbeException(Failure.Header); |
| 146 | } |
| 147 | var flags = HeaderByte(); |
| 148 | if ((flags & 0xe0) != 0) { throw new ProbeException(Failure.Header); } |
| 149 | for (var i = 0; i < 6; i++) { HeaderByte(); } |
| 150 | if ((flags & 4) != 0) |
| 151 | { |
| 152 | var length = HeaderByte() | (HeaderByte() << 8); |
| 153 | for (var i = 0; i < length; i++) { HeaderByte(); } |
| 154 | } |
| 155 | if ((flags & 8) != 0) { while (HeaderByte() != 0) { } } |
| 156 | if ((flags & 16) != 0) { while (HeaderByte() != 0) { } } |
| 157 | if ((flags & 2) != 0) |
| 158 | { |
| 159 | var expected = (ushort)headerCrc.Value; |
| 160 | budget.ChargeMetadata(); |
| 161 | var low = cursor.Byte(); |
| 162 | budget.ChargeMetadata(); |
| 163 | var high = cursor.Byte(); |
| 164 | if ((low | (high << 8)) != expected) { throw new ProbeException(Failure.Header); } |
| 165 | } |
| 166 | var headerBytes = cursor.Position; |
| 167 | inflater ??= new SharpInflater(); |
| 168 | if (inflater.TotalIn != 0 || inflater.TotalOut != 0 || inflater.RemainingInput != 0 || inflater.IsFinished) |
| 169 | { |
| 170 | throw new ProbeException(Failure.Boundary); |
| 171 | } |
| 172 | var compressed = new byte[ProbeBudget.ChunkSize]; |
| 173 | var output = new byte[ProbeBudget.ChunkSize]; |
| 174 | var crc = new Crc32(); |
| 175 | long offered = 0; |
| 176 | long decoded = 0; |
| 177 | while (!inflater.IsFinished) |
| 178 | { |
| 179 | budget.Check(token); |
| 180 | if (inflater.IsNeedingDictionary) { throw new ProbeException(Failure.Deflate); } |
| 181 | if (inflater.IsNeedingInput) |
| 182 | { |
| 183 | var count = cursor.Copy(compressed, feedSize); |
| 184 | if (count == 0) { throw new ProbeException(Failure.Truncated); } |
| 185 | inflater.SetInput(compressed, count); |
| 186 | offered += count; |
| 187 | } |
| 188 | var before = inflater.TotalIn; |
| 189 | var beforeOut = inflater.TotalOut; |
| 190 | int written; |
| 191 | try { written = inflater.Inflate(output); } |
| 192 | catch (SharpZipBaseException) { throw new ProbeException(Failure.Deflate); } |
| 193 | finally |
| 194 | { |
| 195 | // 예외와 반환 직후 취소보다 먼저 실제 출력 증가분을 누적함. |
| 196 | var produced = inflater.TotalOut - beforeOut; |
| 197 | if (produced < 0 || produced > output.Length) { throw new ProbeException(Failure.Boundary); } |
| 198 | budget.ChargeDecoded((int)produced); |
| 199 | } |
| 200 | budget.Check(token); |
| 201 | if (written < 0 || written > output.Length || inflater.TotalIn < before || |
| 202 | inflater.TotalIn > offered || inflater.RemainingInput < 0 || |
| 203 | inflater.TotalIn != offered - inflater.RemainingInput || |
| 204 | inflater.TotalOut != decoded + written) |
| 205 | { |
| 206 | throw new ProbeException(Failure.Boundary); |
| 207 | } |
| 208 | if (written > 0) |
| 209 | { |
| 210 | decoded += written; |
| 211 | crc.Update(new ArraySegment<byte>(output, 0, written)); |
| 212 | if (selected) |
| 213 | { |
| 214 | budget.ChargeOutput(written); |
| 215 | sink(output.AsMemory(0, written)); |
| 216 | budget.Check(token); |
| 217 | } |
| 218 | } |
| 219 | if (written == 0 && inflater.TotalIn == before && !inflater.IsFinished && !inflater.IsNeedingInput) |
| 220 | { |
| 221 | throw new ProbeException(Failure.NoProgress); |
| 222 | } |
| 223 | } |
| 224 | budget.Check(token); |
| 225 | if (inflater.IsNeedingDictionary || inflater.TotalIn != offered - inflater.RemainingInput || |
| 226 | inflater.TotalOut != decoded) |
| 227 | { |
| 228 | throw new ProbeException(Failure.Boundary); |
| 229 | } |
| 230 | var readAhead = inflater.RemainingInput; |
| 231 | var boundary = checked(headerBytes + (int)inflater.TotalIn); |
| 232 | if (cursor.Position - boundary != readAhead) { throw new ProbeException(Failure.Boundary); } |
| 233 | // 원본 메모리의 미소비 꼬리를 다시 읽음. 선행 읽기 바이트를 중복 과금하지 않음. |
| 234 | cursor.Rewind(boundary); |
| 235 | Span<byte> trailer = stackalloc byte[8]; |
| 236 | for (var i = 0; i < trailer.Length; i++) { trailer[i] = cursor.Byte(); } |
| 237 | if (BinaryPrimitives.ReadUInt32LittleEndian(trailer) != (uint)crc.Value) |
| 238 | { |
| 239 | throw new ProbeException(Failure.Crc); |
| 240 | } |
| 241 | if (BinaryPrimitives.ReadUInt32LittleEndian(trailer[4..]) != unchecked((uint)decoded)) |
| 242 | { |
| 243 | throw new ProbeException(Failure.Size); |
| 244 | } |
| 245 | // 연결 member는 GZip 규격에서 유효하지만 이 실험의 단일 member 범위에서는 거부함. |
| 246 | if (cursor.Position != input.Length) { throw new ProbeException(Failure.TrailingData); } |
| 247 | budget.Check(token); |
| 248 | return new(headerBytes, inflater.TotalIn, readAhead, decoded, (uint)crc.Value, |
| 249 | cursor.Position, offered, inflater.TotalOut); |
| 250 | } |
| 251 | |
| 252 | private sealed class Cursor(ReadOnlyMemory<byte> input, ProbeBudget budget, CancellationToken token) |
| 253 | { |
| 254 | public int Position { get; private set; } |
| 255 | private int highWater; |
| 256 | |
| 257 | public byte Byte() |
| 258 | { |
| 259 | budget.Check(token); |
| 260 | if (Position == input.Length) { throw new ProbeException(Failure.Truncated); } |
| 261 | Account(Position + 1); |
| 262 | return input.Span[Position++]; |
| 263 | } |
| 264 | |
| 265 | public int Copy(byte[] destination, int max) |
| 266 | { |
| 267 | budget.Check(token); |
| 268 | var count = Math.Min(max, input.Length - Position); |
| 269 | Account(Position + count); |
| 270 | input.Span.Slice(Position, count).CopyTo(destination); |
| 271 | Position += count; |
| 272 | return count; |
| 273 | } |
| 274 | |
| 275 | public void Rewind(int position) |
| 276 | { |
| 277 | if (position < 0 || position > Position) { throw new ProbeException(Failure.Boundary); } |
| 278 | Position = position; |
| 279 | } |
| 280 | |
| 281 | private void Account(int end) |
| 282 | { |
| 283 | if (end > highWater) |
| 284 | { |
| 285 | budget.ChargeProcessed(end - highWater); |
| 286 | highWater = end; |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | } |