-
Notifications
You must be signed in to change notification settings - Fork 26
/
MPQ.cs
773 lines (658 loc) · 26 KB
/
MPQ.cs
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
//
// MPQ.cs
//
// Author:
// Jarl Gullberg <jarl.gullberg@gmail.com>
//
// Copyright (c) 2016 Jarl Gullberg
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// A massive thanks to Justin Olbrantz (Quantam) and Jean-Francois Roy
// (BahamutZERO), whose [documentation of the MPQ
// format](http://wiki.devklog.net/index.php?title=The_MoPaQ_Archive_Format) was
// instrumental for this implementation. Although their wiki is no longer online,
// a backup snapshot taken by the Wayback Machine saved the day. The documentation
// is available upon request.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Warcraft.Core;
using Warcraft.Core.Compression;
using Warcraft.MPQ.Crypto;
using Warcraft.MPQ.FileInfo;
using Warcraft.MPQ.Tables.Block;
using Warcraft.MPQ.Tables.Hash;
using Warcraft.MPQ.Attributes;
namespace Warcraft.MPQ
{
/// <summary>
/// The MPQ class is the superclass for all known versions of the MPQ file format, which is used to store
/// game data for the majority of produced Blizzard Entertainment games. It acts as a loader and extraction
/// class for reading this data, and examining the data structures inside it.
///
/// It should be noted that this is not a speed-oriented or lightweight implementation of the format. This
/// implementation is designed for verbosity, clarity and ease of use at the expense of memory usage. As
/// a side effect, file lookups may be faster than other implementations, depending on your setup.
///
/// Currently, the class does not support creating new archives, nor any format versions above
/// <see cref="MPQFormat.ExtendedV1"/>. Work is ongoing to implement this.
/// </summary>
public sealed class MPQ : IDisposable, IPackage
{
/// <summary>
/// Whether or not this instance has been disposed.
/// </summary>
private bool IsDisposed;
/// <summary>
/// The header of the MPQ archive. Contains information about sizes and offsets of relational structures
/// such as the hash and block table in the archive.
/// </summary>
public MPQHeader Header;
/// <summary>
/// The hash table. Contains hash entries for all files stored in the archive, and for any overrides.
/// </summary>
public HashTable ArchiveHashTable;
/// <summary>
/// The block table. Contains block entries for all files stored in the archive. These entries contain
/// information about the state of the file.
/// </summary>
public BlockTable ArchiveBlockTable;
/// <summary>
/// The extended block table. Contains a list of upper bits of a ulong number, which is in later versions
/// of the archive format merged with the offset listed in the block table. This format extension allows
/// archives to grow larger than 4GB in size.
/// </summary>
public readonly List<ushort> ExtendedBlockTable = new List<ushort>();
/// <summary>
/// A set of extended file attributes. These attributes are not guaranteed to be present in all archives,
/// and may be empty or zeroed for some archives.
/// </summary>
private ExtendedAttributes FileAttributes;
/// <summary>
/// The archive reader. A BinaryReader that exists for the lifetime of the MPQ object and handles all
/// the file reading inside it. As archives are far too big to be loaded into memory all at once,
/// we seek to the desired parts and read them as we need them.
/// </summary>
private readonly BinaryReader ArchiveReader;
/// <summary>
/// The external listfile. Instead of extracting the listfile from the archive, the user can provide one
/// to be used instead. This file is prioritized over the one stored in the archive.
/// </summary>
private List<string> ExternalListfile = new List<string>();
/// <summary>
/// Initializes a new instance of the <see cref="Warcraft.MPQ.MPQ"/> class.
/// This constructor creates an empty archive.
/// </summary>
/// <param name="inFormat">In format.</param>
public MPQ(MPQFormat inFormat)
{
if (inFormat > MPQFormat.ExtendedV1)
{
throw new NotImplementedException();
}
this.Header = new MPQHeader(inFormat);
this.ArchiveHashTable = new HashTable();
this.ArchiveBlockTable = new BlockTable();
}
/// <summary>
/// Initializes a new instance of the <see cref="Warcraft.MPQ.MPQ"/> class.
/// </summary>
/// <param name="mpqStream">An open stream to data containing an MPQ archive.</param>
public MPQ(Stream mpqStream)
{
this.ArchiveReader = new BinaryReader(mpqStream);
this.Header = new MPQHeader(this.ArchiveReader.ReadBytes((int) PeekHeaderSize()));
// Seek to the hash table and load it
this.ArchiveReader.BaseStream.Position = (long) this.Header.GetHashTableOffset();
byte[] hashTableData;
if (this.Header.IsHashTableCompressed())
{
byte[] encryptedData = this.ArchiveReader.ReadBytes((int) this.Header.GetCompressedHashTableSize());
byte[] decryptedData = MPQCrypt.DecryptData(encryptedData, HashTable.TableKey);
BlockFlags tableFlags = BlockFlags.IsCompressedMultiple;
hashTableData = Compression.DecompressSector(decryptedData, tableFlags);
}
else
{
byte[] encryptedData = this.ArchiveReader.ReadBytes((int) this.Header.GetHashTableSize());
hashTableData = MPQCrypt.DecryptData(encryptedData, HashTable.TableKey);
}
this.ArchiveHashTable = new HashTable(hashTableData);
// Seek to the block table and load it
this.ArchiveReader.BaseStream.Position = (long) this.Header.GetBlockTableOffset();
byte[] blockTableData;
if (this.Header.IsBlockTableCompressed())
{
byte[] encryptedData = this.ArchiveReader.ReadBytes((int) this.Header.GetCompressedBlockTableSize());
byte[] decryptedData = MPQCrypt.DecryptData(encryptedData, BlockTable.TableKey);
BlockFlags tableFlags = BlockFlags.IsCompressedMultiple;
blockTableData = Compression.DecompressSector(decryptedData, tableFlags);
}
else
{
byte[] encryptedData = this.ArchiveReader.ReadBytes((int) this.Header.GetBlockTableSize());
blockTableData = MPQCrypt.DecryptData(encryptedData, BlockTable.TableKey);
}
this.ArchiveBlockTable = new BlockTable(blockTableData);
// TODO: Seek to the extended hash table and load it
// TODO: Seek to the extended block table and load it
if (this.Header.GetFormat() >= MPQFormat.ExtendedV1)
{
// Seek to the extended block table and load it, if neccesary
if (this.Header.GetExtendedBlockTableOffset() <= 0)
{
return;
}
this.ArchiveReader.BaseStream.Position = (long) this.Header.GetExtendedBlockTableOffset();
for (int i = 0; i < this.Header.GetBlockTableEntryCount(); ++i)
{
this.ExtendedBlockTable.Add(this.ArchiveReader.ReadUInt16());
}
}
}
/// <summary>
/// Peeks at the size of the entire MPQ header without advancing the byte position of the
/// binary reader.
/// </summary>
/// <returns>The header size.</returns>
private uint PeekHeaderSize()
{
long originalPosition = this.ArchiveReader.BaseStream.Position;
this.ArchiveReader.BaseStream.Position = 4;
uint headerSize = this.ArchiveReader.ReadUInt32();
this.ArchiveReader.BaseStream.Position = originalPosition;
return headerSize;
}
/// <summary>
/// Determines whether this archive has file attributes.
/// </summary>
/// <returns><c>true</c> if this archive has file attributes; otherwise, <c>false</c>.</returns>
public bool HasFileAttributes()
{
ThrowIfDisposed();
return ContainsFile(ExtendedAttributes.InternalFileName);
}
/// <summary>
/// Gets the extended file attributes stored in the archive, if there are any.
/// </summary>
public ExtendedAttributes GetFileAttributes()
{
ThrowIfDisposed();
if (this.FileAttributes != null)
{
return this.FileAttributes;
}
if (ContainsFile(ExtendedAttributes.InternalFileName))
{
byte[] attributeData = ExtractFile(ExtendedAttributes.InternalFileName);
this.FileAttributes = new ExtendedAttributes(attributeData, this.Header.BlockTableEntryCount);
}
return this.FileAttributes;
}
/// <summary>
/// Gets the weak signature stored in the archive.
/// </summary>
/// <returns>The weak signature.</returns>
public WeakPackageSignature GetWeakSignature()
{
ThrowIfDisposed();
return new WeakPackageSignature(ExtractFile(WeakPackageSignature.InternalFilename));
}
/// <summary>
/// Determines whether this archive has a listfile.
/// </summary>
/// <returns><c>true</c> if this archive has a listfile; otherwise, <c>false</c>.</returns>
public bool HasFileList()
{
ThrowIfDisposed();
return ContainsFile("(listfile)") || this.ExternalListfile.Count > 0;
}
/// <summary>
/// Gets the best available listfile from the archive. If an external listfile has been provided,
/// that one is prioritized over the one stored in the archive.
/// </summary>
/// <returns>The listfile.</returns>
public IEnumerable<string> GetFileList()
{
ThrowIfDisposed();
if (this.ExternalListfile.Count > 0)
{
return GetExternalFileList();
}
return GetInternalFileList();
}
/// <summary>
/// Gets the internal file list. If no listfile is stored in the archive, this may not return anything.
/// </summary>
/// <returns>The internal file list.</returns>
public IEnumerable<string> GetInternalFileList()
{
ThrowIfDisposed();
if (!ContainsFile("(listfile)"))
{
yield break;
}
byte[] listfileBytes = ExtractFile("(listfile)");
using (MemoryStream listfileStream = new MemoryStream(listfileBytes))
{
using (TextReader tr = new StreamReader(listfileStream))
{
string line;
while ((line = tr.ReadLine()) != null)
{
yield return line;
}
}
}
}
/// <summary>
/// Gets the external file list. If no list has been provided to the archive, this may
/// return an empty list.
/// </summary>
/// <returns>The external file list.</returns>
/// <exception cref="ObjectDisposedException">Thrown if the archive has been disposed.</exception>
public IEnumerable<string> GetExternalFileList()
{
ThrowIfDisposed();
return this.ExternalListfile;
}
/// <summary>
/// Sets the file list to the provided listfile.
/// </summary>
/// <param name="inExternalListfile">In external listfile.</param>
/// <exception cref="ObjectDisposedException">Thrown if the archive has been disposed.</exception>
public void SetFileList(List<string> inExternalListfile)
{
ThrowIfDisposed();
this.ExternalListfile = inExternalListfile;
}
/// <summary>
/// Resets the external file list, clearing it of any entries. The internal list file (if there is one)
/// will be used instead.
/// </summary>
/// <exception cref="ObjectDisposedException">Thrown if the archive has been disposed.</exception>
public void ResetExternalFileList()
{
ThrowIfDisposed();
this.ExternalListfile.Clear();
}
/// <inheritdoc />
/// <exception cref="ObjectDisposedException">Thrown if the archive has been disposed.</exception>
public bool ContainsFile(string filePath)
{
ThrowIfDisposed();
try
{
this.ArchiveHashTable.FindEntry(filePath.ToUpperInvariant());
}
catch (FileNotFoundException)
{
return false;
}
return true;
}
/// <inheritdoc />
/// <exception cref="ObjectDisposedException">Thrown if the archive has been disposed.</exception>
/// <exception cref="FileNotFoundException">Thrown if the archive does not contain a file at the given path.</exception>
public MPQFileInfo GetFileInfo(string filePath)
{
ThrowIfDisposed();
if (!ContainsFile(filePath))
{
throw new FileNotFoundException("The given file was not present in the archive.", filePath);
}
HashTableEntry hashEntry = this.ArchiveHashTable.FindEntry(filePath);
BlockTableEntry blockEntry = this.ArchiveBlockTable.GetEntry((int)hashEntry.GetBlockEntryIndex());
if (HasFileAttributes())
{
return new MPQFileInfo(filePath, hashEntry, blockEntry);
}
return new MPQFileInfo(filePath, hashEntry, blockEntry, this.FileAttributes.FileAttributes[(int)hashEntry.GetBlockEntryIndex()]);
}
/// <inheritdoc />
/// <exception cref="ObjectDisposedException">Thrown if the archive has been disposed.</exception>
/// <exception cref="FileNotFoundException">Thrown if the archive does not contain a file at the given path.</exception>
/// <exception cref="FileDeletedException">Thrown if the file is deleted in the archive.</exception>
public byte[] ExtractFile(string filePath)
{
ThrowIfDisposed();
// Reset all positions to be safe
this.ArchiveReader.BaseStream.Position = 0;
HashTableEntry fileHashEntry;
try
{
fileHashEntry = this.ArchiveHashTable.FindEntry(filePath);
}
catch (FileNotFoundException fex)
{
throw new FileNotFoundException("No file found at the given path.", filePath, fex);
}
BlockTableEntry fileBlockEntry = this.ArchiveBlockTable.GetEntry((int)fileHashEntry.GetBlockEntryIndex());
// Drop out if the file has been deleted
if (fileBlockEntry.IsDeleted())
{
throw new FileDeletedException("The given file is deleted.", filePath);
}
// Seek to the beginning of the file's sectors
long adjustedBlockOffset;
if (this.Header.GetFormat() >= MPQFormat.ExtendedV1 && RequiresExtendedFormat())
{
ushort upperOffsetBits = this.ExtendedBlockTable[(int)fileHashEntry.GetBlockEntryIndex()];
adjustedBlockOffset = (long)fileBlockEntry.GetExtendedBlockOffset(upperOffsetBits);
}
else
{
adjustedBlockOffset = fileBlockEntry.GetBlockOffset();
}
this.ArchiveReader.BaseStream.Position = adjustedBlockOffset;
// Calculate the decryption key if neccesary
uint fileKey = MPQCrypt.CreateFileEncryptionKey
(
filePath,
fileBlockEntry.ShouldEncryptionKeyBeAdjusted(),
adjustedBlockOffset,
fileBlockEntry.GetFileSize()
);
// Examine the file storage types and extract as neccesary
if (fileBlockEntry.IsSingleUnit())
{
return ExtractSingleUnitFile(fileBlockEntry, fileKey);
}
if (fileBlockEntry.IsCompressed())
{
return ExtractCompressedSectoredFile(fileBlockEntry, fileKey, adjustedBlockOffset);
}
return ExtractUncompressedSectoredFile(fileBlockEntry, fileKey);
}
/// <summary>
/// Extracts a file which is divided into a set of compressed sectors.
/// </summary>
/// <param name="fileBlockEntry">The block entry of the file.</param>
/// <param name="fileKey">The encryption key of the file.</param>
/// <param name="adjustedBlockOffset">The offset to where the file sectors begin.</param>
/// <returns>The complete file data.</returns>
/// <exception cref="InvalidFileSectorTableException">Thrown if the sector table is found to be inconsistent in any way.</exception>
private byte[] ExtractCompressedSectoredFile(BlockTableEntry fileBlockEntry, uint fileKey, long adjustedBlockOffset)
{
// This file uses sectoring, and is compressed. It may be encrypted.
//Retrieve the offsets for each sector - these are relative to the beginning of the data.
List<uint> sectorOffsets = ReadFileSectorOffsetTable(fileBlockEntry, fileKey);
// Read all of the raw file sectors.
List<byte[]> compressedSectors = new List<byte[]>();
for (int i = 0; i < sectorOffsets.Count - 1; ++i)
{
long sectorStartPosition = adjustedBlockOffset + sectorOffsets[i];
this.ArchiveReader.BaseStream.Position = sectorStartPosition;
uint sectorLength = sectorOffsets[i + 1] - sectorOffsets[i];
compressedSectors.Add(this.ArchiveReader.ReadBytes((int) sectorLength));
}
// Begin decompressing and decrypting the sectors
// TODO: If Checksums are present (check the flags), treat the last sector as a checksum sector
// TODO: Check "backup.MPQ/realmlist.wtf" for a weird file with checksums that is not working correctly.
// It has a single sector with a single checksum after it, and none of the hashing functions seem to
// produce a valid hash. CRC32, Adler32, CRC32B, nothing.
// Some flags (listfiles mostly) are flagged as having checksums but don't have a checksum sector.
// Perhaps related to attributes file?
List<byte[]> decompressedSectors = new List<byte[]>();
/* List<uint> SectorChecksums = new List<uint>();
if (fileBlockEntry.Flags.HasFlag(BlockFlags.BLF_HasChecksums))
{
byte[] compressedChecksums = compressedSectors.Last();
byte[] decompressedChecksums = Compression.DecompressSector(compressedChecksums, fileBlockEntry.Flags);
// Lift out the last sector and treat it as a checksum sector
using (MemoryStream ms = new MemoryStream(decompressedChecksums))
{
using (BinaryReader br = new BinaryReader(ms))
{
// Drop the checksum sector from the file sectors
compressedSectors.RemoveAt(compressedSectors.Count - 1);
for (int i = 0; i < compressedSectors.Count; ++i)
{
SectorChecksums.Add(br.ReadUInt32());
}
}
}
}*/
uint sectorIndex = 0;
foreach (byte[] compressedSector in compressedSectors)
{
byte[] pendingSector = compressedSector;
if (fileBlockEntry.IsEncrypted())
{
// Decrypt the block
pendingSector = MPQCrypt.DecryptData(compressedSector, fileKey + sectorIndex);
}
/*if (fileBlockEntry.Flags.HasFlag(BlockFlags.HasCRCChecksums))
{
// Verify the sector
bool isSectorIntact = MPQCrypt.VerifySectorChecksum(pendingSector, SectorChecksums[(int)sectorIndex]);
if (!isSectorIntact)
{
using (MemoryStream ms = new MemoryStream(pendingSector))
{
//DEBUG
uint sectorChecksum = (uint)Adler32.ComputeChecksum(ms);
string exceptionMessage = String.Format("The decrypted sector failed its integrity checking. \n" +
"The sector had a checksum of \"{0}\", and the expected one was \"{1}\".",
sectorChecksum, SectorChecksums[(int)sectorIndex]);
throw new InvalidDataException(exceptionMessage);
}
}
}*/
// Decompress the sector if neccesary
if (pendingSector.Length < GetMaxSectorSize())
{
int currentFileSize = CountBytesInSectors(decompressedSectors);
bool canSectorCompleteFile = currentFileSize + pendingSector.Length == fileBlockEntry.GetFileSize();
if (!canSectorCompleteFile && currentFileSize != fileBlockEntry.GetFileSize())
{
pendingSector = Compression.DecompressSector(pendingSector, fileBlockEntry.Flags);
}
}
decompressedSectors.Add(pendingSector);
++sectorIndex;
}
return StitchSectors(decompressedSectors);
}
/// <summary>
/// Reads the sector offset table of a file.
/// </summary>
/// <param name="fileBlockEntry">The block table entry of the file.</param>
/// <param name="fileKey">The encryption key of the file. Optional, in the case that the file is not encrypted.</param>
/// <returns>A list of sector offsets.</returns>
/// <exception cref="InvalidFileSectorTableException">Thrown if the sector table is found to be inconsistent in any way.</exception>
private List<uint> ReadFileSectorOffsetTable(BlockTableEntry fileBlockEntry, uint fileKey = 0)
{
List<uint> sectorOffsets = new List<uint>();
if (fileBlockEntry.IsEncrypted())
{
MPQCrypt.DecryptSectorOffsetTable(this.ArchiveReader, ref sectorOffsets, fileBlockEntry.GetBlockSize(), fileKey - 1);
}
else
{
// As protection against corrupt or maliciously zeroed blocks or corrupt blocks,
// reading will be escaped early if the sector offset table is not consistent.
// Should the total size as predicted by the sector offset table go beyond the total
// block size, or if an offset is not unique, no file will be read and the function will
// escape early.
uint sectorOffset = 0;
while (sectorOffset != fileBlockEntry.GetBlockSize())
{
sectorOffset = this.ArchiveReader.ReadUInt32();
// Should the resulting sector offset be less than the previous data, then the data is inconsistent
// and no table should be returned.
if (sectorOffsets.LastOrDefault() > sectorOffset)
{
throw new InvalidFileSectorTableException(
"The read offset in the sector table was less than the previous offset.");
}
// Should the resulting sector offset be greater than the total block size, then the data is
// inconsistent and no file should be returned.
if (sectorOffset > fileBlockEntry.GetBlockSize())
{
throw new InvalidFileSectorTableException(
"The read offset in the sector table was greater than the total size of the data block.");
}
// Should the resulting sector not be unique, something is wrong and no table should be returned.
if (sectorOffsets.Contains(sectorOffset))
{
throw new InvalidFileSectorTableException(
"The read offset in the sector table was not unique to the whole table.");
}
// The offset should be valid, so add it to the table.
sectorOffsets.Add(sectorOffset);
}
}
return sectorOffsets;
}
/// <summary>
/// Extracts a file which is divided into a set ofsectors.
/// </summary>
/// <param name="fileBlockEntry">The block entry of the file.</param>
/// <param name="fileKey">The encryption key of the file.</param>
/// <returns>The complete file data.</returns>
private byte[] ExtractUncompressedSectoredFile(BlockTableEntry fileBlockEntry, uint fileKey)
{
// This file uses sectoring, but is not compressed. It may be encrypted.
uint finalSectorSize = fileBlockEntry.GetFileSize() % GetMaxSectorSize();
// All the even sectors you can fit into the file size
uint sectorCount = ((fileBlockEntry.GetFileSize() - finalSectorSize) / GetMaxSectorSize());
List<byte[]> rawSectors = new List<byte[]>();
for (int i = 0; i < sectorCount; ++i)
{
// Read a normal sector (usually 4096 bytes)
rawSectors.Add(this.ArchiveReader.ReadBytes((int) GetMaxSectorSize()));
}
// And finally, if there's an uneven sector at the end, read that one too
if (finalSectorSize > 0)
{
rawSectors.Add(this.ArchiveReader.ReadBytes((int) finalSectorSize));
}
uint sectorIndex = 0;
List<byte[]> finalSectors = new List<byte[]>();
foreach (byte[] rawSector in rawSectors)
{
byte[] pendingSector = rawSector;
if (fileBlockEntry.IsEncrypted())
{
// Decrypt the block
pendingSector = MPQCrypt.DecryptData(rawSector, fileKey + sectorIndex);
}
finalSectors.Add(pendingSector);
++sectorIndex;
}
return StitchSectors(finalSectors);
}
/// <summary>
/// Extracts a file which is stored as a single unit in the archive.
/// </summary>
/// <param name="fileBlockEntry">The block entry of the file.</param>
/// <param name="fileKey">The encryption key of the file.</param>
/// <returns>The complete file data.</returns>
private byte[] ExtractSingleUnitFile(BlockTableEntry fileBlockEntry, uint fileKey)
{
// This file does not use sectoring, but may still be encrypted or compressed.
byte[] fileData = this.ArchiveReader.ReadBytes((int) fileBlockEntry.GetBlockSize());
if (fileBlockEntry.IsEncrypted())
{
// Decrypt the block
fileData = MPQCrypt.DecryptData(fileData, fileKey);
}
// Decompress the sector if neccesary
if (fileBlockEntry.IsCompressed())
{
fileData = Compression.DecompressSector(fileData, fileBlockEntry.Flags);
}
return fileData;
}
/// <summary>
/// Counts the bytes contained in a list of sectors.
/// </summary>
/// <returns>The number of bytes.</returns>
/// <param name="sectors">The sectors.</param>
private static int CountBytesInSectors(IEnumerable<byte[]> sectors)
{
return sectors.Sum(sector => sector.Length);
}
/// <summary>
/// Stitches together a set of file sectors into a final byte list, which can then be used for other things.
/// </summary>
/// <returns>A byte array representing the final file.</returns>
/// <param name="sectors">Input file sectors.</param>
private static byte[] StitchSectors(IReadOnlyCollection<byte[]> sectors)
{
long finalSize = 0;
foreach (byte[] sector in sectors)
{
finalSize += sector.Length;
}
byte[] finalBlock = new byte[finalSize];
// Pull out your sowing kit, it's stitching time!
int writtenBytes = 0;
foreach (byte[] sector in sectors)
{
Buffer.BlockCopy(sector, 0, finalBlock, writtenBytes, sector.Length);
writtenBytes += sector.Length;
}
return finalBlock;
}
/// <summary>
/// Determines whether or not the archive requires the format to be extended.
/// ExtendedIO formats are at least <see cref="MPQFormat.ExtendedV1"/> and up.
/// </summary>
/// <returns><c>true</c>, if extended format is required, <c>false</c> otherwise.</returns>
private bool RequiresExtendedFormat()
{
return this.ArchiveReader.BaseStream.Length > uint.MaxValue;
}
/// <summary>
/// Gets the maximum size of a file sector.
/// </summary>
/// <returns>The max sector size.</returns>
private uint GetMaxSectorSize()
{
return (uint)(512 * Math.Pow(2, this.Header.GetSectorSizeExponent()));
}
private void ThrowIfDisposed()
{
if (this.IsDisposed)
{
throw new ObjectDisposedException(ToString(), "Cannot use a disposed archive.");
}
}
/// <inheritdoc />
public void Dispose()
{
this.Header = null;
this.ArchiveHashTable = null;
this.ArchiveBlockTable = null;
if (this.ExtendedBlockTable.Count > 0)
{
this.ExtendedBlockTable.Clear();
}
if (this.ExternalListfile.Count > 0)
{
this.ExternalListfile.Clear();
}
if (this.ArchiveReader != null)
{
this.ArchiveReader.Close();
this.ArchiveReader.Dispose();
}
this.IsDisposed = true;
}
}
}