| 1 | using System.Buffers.Binary; |
| 2 | using System.IO.Compression; |
| 3 | using System.Text; |
| 4 | using Zipelo.Core; |
| 5 | using Zipelo.Runtime; |
| 6 | |
| 7 | namespace Zipelo.Worker; |
| 8 | |
| 9 | // 초기 해제는 단일 디스크 ZIP32의 저장/Deflate 방식만 허용함. |
| 10 | internal static class ZipExtractor |
| 11 | { |
| 12 | private sealed record Item(ArchiveEntry Entry, uint Crc, int Start, int Packed, int Method); |
| 13 | |
| 14 | internal static ZipWorkerResult Extract(WorkerRequest request, CancellationToken token) |
| 15 | { |
| 16 | try |
| 17 | { |
| 18 | var budget = new JobBudget(request.Limits); |
| 19 | var bytes = request.Inputs.Single(); |
| 20 | budget.ChargeProcessed(bytes.Length, token); |
| 21 | var items = Parse(bytes, budget, token); |
| 22 | ZipExtraction.ValidatePaths(items.Select(item => item.Entry).ToArray()); |
| 23 | var outputs = new List<ZipExtractedEntry>(); |
| 24 | long total = 0; |
| 25 | var buffer = new byte[65536]; |
| 26 | foreach (var item in items) |
| 27 | { |
| 28 | budget.Check(token); |
| 29 | using var packed = new MemoryStream(bytes, item.Start, item.Packed, writable: false); |
| 30 | using Stream decoded = item.Method == 0 ? packed : new DeflateStream(packed, CompressionMode.Decompress); |
| 31 | using var output = new MemoryStream(); |
| 32 | var crc = uint.MaxValue; |
| 33 | int count; |
| 34 | while ((count = decoded.Read(buffer, 0, buffer.Length)) != 0) |
| 35 | { |
| 36 | budget.ChargeProcessed(count, token); |
| 37 | budget.ReserveOutput(count, token); |
| 38 | total += count; |
| 39 | if (total > WorkerProtocol.MaxDataBytes) { throw new ArchiveException(ArchiveError.BudgetExceeded); } |
| 40 | if (output.Length + count > item.Entry.DeclaredSize) |
| 41 | { |
| 42 | throw new ArchiveException(ArchiveError.IntegrityFailure); |
| 43 | } |
| 44 | crc = ZipExtraction.UpdateCrc(crc, buffer.AsSpan(0, count)); |
| 45 | output.Write(buffer, 0, count); |
| 46 | } |
| 47 | budget.Check(token); |
| 48 | if (output.Length != item.Entry.DeclaredSize || ~crc != item.Crc) |
| 49 | { |
| 50 | throw new ArchiveException(ArchiveError.IntegrityFailure); |
| 51 | } |
| 52 | outputs.Add(new(item.Entry, output.ToArray(), item.Crc)); |
| 53 | } |
| 54 | var reports = outputs.Select(item => new EntryResult(item.Entry, EntryOutcome.Staged, |
| 55 | VerificationState.Passed, ArchiveError.None)).ToArray(); |
| 56 | budget.Check(token); |
| 57 | return new(new(request.JobId, JobState.Completed, reports, ArchiveError.None), null) |
| 58 | { |
| 59 | ExtractedEntries = outputs.ToArray() |
| 60 | }; |
| 61 | } |
| 62 | catch (InvalidDataException) { throw new ArchiveException(ArchiveError.IntegrityFailure); } |
| 63 | catch (DecoderFallbackException) { throw new ArchiveException(ArchiveError.UnsafePath); } |
| 64 | catch (OverflowException) { throw new ArchiveException(ArchiveError.IntegrityFailure); } |
| 65 | } |
| 66 | |
| 67 | private static Item[] Parse(byte[] data, JobBudget budget, CancellationToken token) |
| 68 | { |
| 69 | int U16(int offset) => BinaryPrimitives.ReadUInt16LittleEndian(Slice(data, offset, 2)); |
| 70 | uint U32(int offset) => BinaryPrimitives.ReadUInt32LittleEndian(Slice(data, offset, 4)); |
| 71 | int Size(int offset) => checked((int)U32(offset)); |
| 72 | var end = data.Length - 22; |
| 73 | while (end >= Math.Max(0, data.Length - 65557)) |
| 74 | { |
| 75 | if (U32(end) == 0x06054B50 && end + 22 + U16(end + 20) == data.Length) { break; } |
| 76 | end--; |
| 77 | } |
| 78 | if (end < Math.Max(0, data.Length - 65557)) { throw new ArchiveException(ArchiveError.IntegrityFailure); } |
| 79 | if (U16(end + 4) != 0 || U16(end + 6) != 0 || U16(end + 8) != U16(end + 10) || U16(end + 10) == 65535) |
| 80 | { |
| 81 | throw new ArchiveException(ArchiveError.UnsupportedOperation); |
| 82 | } |
| 83 | var count = U16(end + 10); |
| 84 | if (count > WorkerProtocol.MaxEntries) { throw new ArchiveException(ArchiveError.BudgetExceeded); } |
| 85 | var central = Size(end + 16); |
| 86 | if ((long)central + Size(end + 12) != end) { throw new ArchiveException(ArchiveError.IntegrityFailure); } |
| 87 | var cursor = central; |
| 88 | var items = new List<Item>(); |
| 89 | var ranges = new List<(int Start, int End)>(); |
| 90 | for (var index = 0; index < count; index++) |
| 91 | { |
| 92 | budget.AddEntry(token); |
| 93 | _ = Slice(data, cursor, 46); |
| 94 | if (U32(cursor) != 0x02014B50) { throw new ArchiveException(ArchiveError.IntegrityFailure); } |
| 95 | var creator = U16(cursor + 4) >> 8; |
| 96 | var flags = U16(cursor + 8); |
| 97 | var method = U16(cursor + 10); |
| 98 | if (creator is not (0 or 3) || U16(cursor + 6) > 20 || U16(cursor + 34) != 0 || |
| 99 | (flags & ~0x080E) != 0 || method is not (0 or 8)) |
| 100 | { |
| 101 | throw new ArchiveException(ArchiveError.UnsupportedOperation); |
| 102 | } |
| 103 | var crc = U32(cursor + 16); |
| 104 | var packed = Size(cursor + 20); |
| 105 | var unpacked = Size(cursor + 24); |
| 106 | if (method == 8 && packed < 2) { throw new ArchiveException(ArchiveError.IntegrityFailure); } |
| 107 | var nameLength = U16(cursor + 28); |
| 108 | var extraLength = U16(cursor + 30); |
| 109 | var nameBytes = Slice(data, cursor + 46, nameLength); |
| 110 | if ((flags & 0x0800) == 0 && nameBytes.IndexOfAnyInRange((byte)128, (byte)255) >= 0) |
| 111 | { |
| 112 | throw new ArchiveException(ArchiveError.UnsupportedOperation); |
| 113 | } |
| 114 | var name = new UTF8Encoding(false, true).GetString(nameBytes); |
| 115 | var attributes = U32(cursor + 38); |
| 116 | var unixType = (attributes >> 16) & 0xF000; |
| 117 | if (unixType is not (0 or 0x8000 or 0x4000) || (attributes & 0x400) != 0) |
| 118 | { |
| 119 | throw new ArchiveException(ArchiveError.UnsupportedEntry); |
| 120 | } |
| 121 | var directory = name.EndsWith('/'); |
| 122 | if ((unixType == 0x4000 || (attributes & 0x10) != 0) && !directory || |
| 123 | directory && (unixType == 0x8000 || unpacked != 0 || crc != 0)) |
| 124 | { |
| 125 | throw new ArchiveException(ArchiveError.UnsupportedEntry); |
| 126 | } |
| 127 | var path = directory ? name[..^1] : name; |
| 128 | var entry = new ArchiveEntry($"entry-{index}", path, directory ? EntryKind.Directory : EntryKind.File, unpacked); |
| 129 | CheckExtra(Slice(data, cursor + 46 + nameLength, extraLength)); |
| 130 | var local = Size(cursor + 42); |
| 131 | _ = Slice(data, local, 30); |
| 132 | if (U32(local) != 0x04034B50 || U16(local + 4) != U16(cursor + 6) || |
| 133 | U16(local + 6) != flags || U16(local + 8) != method || U16(local + 26) != nameLength || |
| 134 | !Slice(data, local + 30, nameLength).SequenceEqual(nameBytes)) |
| 135 | { |
| 136 | throw new ArchiveException(ArchiveError.IntegrityFailure); |
| 137 | } |
| 138 | if ((flags & 8) == 0 && (U32(local + 14) != crc || Size(local + 18) != packed || Size(local + 22) != unpacked)) |
| 139 | { |
| 140 | throw new ArchiveException(ArchiveError.IntegrityFailure); |
| 141 | } |
| 142 | if ((flags & 8) != 0 && ((U32(local + 14) != 0 && U32(local + 14) != crc) || |
| 143 | (U32(local + 18) != 0 && Size(local + 18) != packed) || |
| 144 | (U32(local + 22) != 0 && Size(local + 22) != unpacked))) |
| 145 | { |
| 146 | throw new ArchiveException(ArchiveError.IntegrityFailure); |
| 147 | } |
| 148 | var localExtra = U16(local + 28); |
| 149 | CheckExtra(Slice(data, local + 30 + nameLength, localExtra)); |
| 150 | var start = checked(local + 30 + nameLength + localExtra); |
| 151 | var finish = checked(start + packed); |
| 152 | _ = Slice(data, start, packed); |
| 153 | if ((flags & 8) != 0) |
| 154 | { |
| 155 | var descriptor = finish; |
| 156 | if (U32(descriptor) == 0x08074B50) { descriptor += 4; } |
| 157 | if (U32(descriptor) != crc || Size(descriptor + 4) != packed || Size(descriptor + 8) != unpacked) |
| 158 | { |
| 159 | throw new ArchiveException(ArchiveError.IntegrityFailure); |
| 160 | } |
| 161 | finish = checked(descriptor + 12); |
| 162 | } |
| 163 | if (finish > central) { throw new ArchiveException(ArchiveError.IntegrityFailure); } |
| 164 | ranges.Add((local, finish)); |
| 165 | items.Add(new(entry, crc, start, packed, method)); |
| 166 | cursor = checked(cursor + 46 + nameLength + extraLength + U16(cursor + 32)); |
| 167 | } |
| 168 | if (cursor != end) { throw new ArchiveException(ArchiveError.IntegrityFailure); } |
| 169 | var next = 0; |
| 170 | foreach (var range in ranges.OrderBy(range => range.Start)) |
| 171 | { |
| 172 | if (range.Start != next) { throw new ArchiveException(ArchiveError.IntegrityFailure); } |
| 173 | next = range.End; |
| 174 | } |
| 175 | if (next != central) { throw new ArchiveException(ArchiveError.IntegrityFailure); } |
| 176 | return items.ToArray(); |
| 177 | } |
| 178 | |
| 179 | private static ReadOnlySpan<byte> Slice(byte[] bytes, int offset, int length) |
| 180 | { |
| 181 | if (offset < 0 || length < 0 || offset > bytes.Length - length) |
| 182 | { |
| 183 | throw new ArchiveException(ArchiveError.IntegrityFailure); |
| 184 | } |
| 185 | return bytes.AsSpan(offset, length); |
| 186 | } |
| 187 | |
| 188 | private static void CheckExtra(ReadOnlySpan<byte> bytes) |
| 189 | { |
| 190 | // 링크 의미를 가진 Unix/ASi 등 미해석 확장 필드는 수용하지 않음. |
| 191 | while (!bytes.IsEmpty) |
| 192 | { |
| 193 | if (bytes.Length < 4) { throw new ArchiveException(ArchiveError.IntegrityFailure); } |
| 194 | var id = BinaryPrimitives.ReadUInt16LittleEndian(bytes); |
| 195 | var size = BinaryPrimitives.ReadUInt16LittleEndian(bytes[2..]); |
| 196 | if (size > bytes.Length - 4) { throw new ArchiveException(ArchiveError.IntegrityFailure); } |
| 197 | if (id != 0x5455) { throw new ArchiveException(ArchiveError.UnsupportedEntry); } |
| 198 | bytes = bytes[(4 + size)..]; |
| 199 | } |
| 200 | } |
| 201 | } |