ZipArchiveStorage.cs
11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
using System.IO.Compression;
using System.Runtime.InteropServices;
/// <summary>
/// https://en.wikipedia.org/wiki/Zip_(file_format)
/// </summary>
namespace UniGLTF.Zip
{
enum CompressionMethod : ushort
{
Stored = 0, // The file is stored (no compression)
Shrink = 1, // The file is Shrunk
Reduced1 = 2, // The file is Reduced with compression factor 1
Reduced2 = 3, // The file is Reduced with compression factor 2
Reduced3 = 4, // The file is Reduced with compression factor 3
Reduced4 = 5, // The file is Reduced with compression factor 4
Imploded = 6, // The file is Imploded
Reserved = 7, // Reserved for Tokenizing compression algorithm
Deflated = 8, // The file is Deflated
}
class ZipParseException : Exception
{
public ZipParseException(string msg) : base(msg)
{ }
}
class EOCD
{
public ushort NumberOfThisDisk;
public ushort DiskWhereCentralDirectoryStarts;
public ushort NumberOfCentralDirectoryRecordsOnThisDisk;
public ushort TotalNumberOfCentralDirectoryRecords;
public int SizeOfCentralDirectoryBytes;
public int OffsetOfStartOfCentralDirectory;
public string Comment;
public override string ToString()
{
return string.Format("<EOCD records: {0}, offset: {1}, '{2}'>",
NumberOfCentralDirectoryRecordsOnThisDisk,
OffsetOfStartOfCentralDirectory,
Comment
);
}
static int FindEOCD(byte[] bytes)
{
for (int i = bytes.Length - 22; i >= 0; --i)
{
if (bytes[i] == 0x50
&& bytes[i + 1] == 0x4b
&& bytes[i + 2] == 0x05
&& bytes[i + 3] == 0x06)
{
return i;
}
}
throw new ZipParseException("EOCD is not found");
}
public static EOCD Parse(Byte[] bytes)
{
var pos = FindEOCD(bytes);
using (var ms = new MemoryStream(bytes, pos, bytes.Length - pos, false))
using (var r = new BinaryReader(ms))
{
var sig = r.ReadInt32();
if (sig != 0x06054b50) throw new ZipParseException("invalid eocd signature: " + sig);
var eocd = new EOCD
{
NumberOfThisDisk = r.ReadUInt16(),
DiskWhereCentralDirectoryStarts = r.ReadUInt16(),
NumberOfCentralDirectoryRecordsOnThisDisk = r.ReadUInt16(),
TotalNumberOfCentralDirectoryRecords = r.ReadUInt16(),
SizeOfCentralDirectoryBytes = r.ReadInt32(),
OffsetOfStartOfCentralDirectory = r.ReadInt32(),
};
var commentLength = r.ReadUInt16();
var commentBytes = r.ReadBytes(commentLength);
eocd.Comment = Encoding.ASCII.GetString(commentBytes);
return eocd;
}
}
}
abstract class CommonHeader
{
public Encoding Encoding = Encoding.UTF8;
public Byte[] Bytes;
public int Offset;
public abstract int Signature
{
get;
}
protected CommonHeader(Byte[] bytes, int offset)
{
var sig = BitConverter.ToInt32(bytes, offset);
if (sig != Signature)
{
throw new ZipParseException("invalid central directory file signature: " + sig);
}
Bytes = bytes;
Offset = offset;
var start = offset + 4;
using (var ms = new MemoryStream(bytes, start, bytes.Length - start, false))
using (var r = new BinaryReader(ms))
{
ReadBefore(r);
Read(r);
ReadAfter(r);
}
}
public UInt16 VersionNeededToExtract;
public UInt16 GeneralPurposeBitFlag;
public CompressionMethod CompressionMethod;
public UInt16 FileLastModificationTime;
public UInt16 FileLastModificationDate;
public Int32 CRC32;
public Int32 CompressedSize;
public Int32 UncompressedSize;
public UInt16 FileNameLength;
public UInt16 ExtraFieldLength;
public abstract int FixedFieldLength
{
get;
}
public abstract int Length
{
get;
}
public string FileName
{
get
{
return Encoding.GetString(Bytes,
Offset + FixedFieldLength,
FileNameLength);
}
}
public ArraySegment<Byte> ExtraField
{
get
{
return new ArraySegment<byte>(Bytes,
Offset + FixedFieldLength + FileNameLength,
ExtraFieldLength);
}
}
public override string ToString()
{
return string.Format("<file {0}({1}/{2} {3})>",
FileName,
CompressedSize,
UncompressedSize,
CompressionMethod
);
}
public abstract void ReadBefore(BinaryReader r);
public void Read(BinaryReader r)
{
VersionNeededToExtract = r.ReadUInt16();
GeneralPurposeBitFlag = r.ReadUInt16();
CompressionMethod = (CompressionMethod)r.ReadUInt16();
FileLastModificationTime = r.ReadUInt16();
FileLastModificationDate = r.ReadUInt16();
CRC32 = r.ReadInt32();
CompressedSize = r.ReadInt32();
UncompressedSize = r.ReadInt32();
FileNameLength = r.ReadUInt16();
ExtraFieldLength = r.ReadUInt16();
}
public abstract void ReadAfter(BinaryReader r);
}
class CentralDirectoryFileHeader : CommonHeader
{
public override int Signature
{
get
{
return 0x02014b50;
}
}
public CentralDirectoryFileHeader(Byte[] bytes, int offset) : base(bytes, offset) { }
public UInt16 VersionMadeBy;
public UInt16 FileCommentLength;
public UInt16 DiskNumberWhereFileStarts;
public UInt16 InternalFileAttributes;
public Int32 ExternalFileAttributes;
public Int32 RelativeOffsetOfLocalFileHeader;
public override int FixedFieldLength
{
get
{
return 46;
}
}
public string FileComment
{
get
{
return Encoding.GetString(Bytes,
Offset + 46 + FileNameLength + ExtraFieldLength,
FileCommentLength);
}
}
public override int Length
{
get
{
return FixedFieldLength + FileNameLength + ExtraFieldLength + FileCommentLength;
}
}
public override void ReadBefore(BinaryReader r)
{
VersionMadeBy = r.ReadUInt16();
}
public override void ReadAfter(BinaryReader r)
{
FileCommentLength = r.ReadUInt16();
DiskNumberWhereFileStarts = r.ReadUInt16();
InternalFileAttributes = r.ReadUInt16();
ExternalFileAttributes = r.ReadInt32();
RelativeOffsetOfLocalFileHeader = r.ReadInt32();
}
}
class LocalFileHeader : CommonHeader
{
public override int FixedFieldLength
{
get
{
return 30;
}
}
public override int Signature
{
get
{
return 0x04034b50;
}
}
public override int Length
{
get
{
return FixedFieldLength + FileNameLength + ExtraFieldLength;
}
}
public LocalFileHeader(Byte[] bytes, int offset) : base(bytes, offset)
{
}
public override void ReadBefore(BinaryReader r)
{
}
public override void ReadAfter(BinaryReader r)
{
}
}
class ZipArchiveStorage : IStorage
{
public override string ToString()
{
return string.Format("<ZIPArchive\n{0}>", String.Join("", Entries.Select(x => x.ToString() + "\n").ToArray()));
}
public List<CentralDirectoryFileHeader> Entries = new List<CentralDirectoryFileHeader>();
public static ZipArchiveStorage Parse(byte[] bytes)
{
var eocd = EOCD.Parse(bytes);
var archive = new ZipArchiveStorage();
var pos = eocd.OffsetOfStartOfCentralDirectory;
for (int i = 0; i < eocd.NumberOfCentralDirectoryRecordsOnThisDisk; ++i)
{
var file = new CentralDirectoryFileHeader(bytes, pos);
archive.Entries.Add(file);
pos += file.Length;
}
return archive;
}
public Byte[] Extract(CentralDirectoryFileHeader header)
{
var local = new LocalFileHeader(header.Bytes, header.RelativeOffsetOfLocalFileHeader);
var pos = local.Offset + local.Length;
var dst = new Byte[local.UncompressedSize];
#if true
using (var s = new MemoryStream(header.Bytes, pos, local.CompressedSize, false))
using (var deflateStream = new DeflateStream(s, CompressionMode.Decompress))
{
int dst_pos = 0;
for (int remain = dst.Length; remain > 0;)
{
var readSize = deflateStream.Read(dst, dst_pos, remain);
dst_pos += readSize;
remain -= readSize;
}
}
#else
var size=RawInflate.RawInflateImport.RawInflate(dst, 0, dst.Length,
header.Bytes, pos, header.CompressedSize);
#endif
return dst;
}
public string ExtractToString(CentralDirectoryFileHeader header, Encoding encoding)
{
var local = new LocalFileHeader(header.Bytes, header.RelativeOffsetOfLocalFileHeader);
var pos = local.Offset + local.Length;
using (var s = new MemoryStream(header.Bytes, pos, local.CompressedSize, false))
using (var deflateStream = new DeflateStream(s, CompressionMode.Decompress))
using (var r = new StreamReader(deflateStream, encoding))
{
return r.ReadToEnd();
}
}
public ArraySegment<byte> Get(string url)
{
var found = Entries.FirstOrDefault(x => x.FileName == url);
if (found == null)
{
throw new FileNotFoundException("[ZipArchive]" + url);
}
switch (found.CompressionMethod)
{
case CompressionMethod.Deflated:
return new ArraySegment<byte>(Extract(found));
case CompressionMethod.Stored:
return new ArraySegment<byte>(found.Bytes, found.RelativeOffsetOfLocalFileHeader, found.CompressedSize);
}
throw new NotImplementedException(found.CompressionMethod.ToString());
}
public string GetPath(string url)
{
return null;
}
}
}