forked from No-Bling/DOTA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vpkmod.cs
2749 lines (2400 loc) · 122 KB
/
vpkmod.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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Windows.Forms;
using System.Drawing; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Text;
using System.Net; using SteamDatabase.ValvePak; using SteamKit.KeyValue; [assembly:AssemblyDescriptionAttribute(@"
`````` ````````` ` ````````````````````````````````````` ``
``:#################:`````````:#########:``````:############:``:#######:`
``:######################################:``:#######################:``
```:#############################################################:```
```:#############################################################:```
```:#############################################################:```
````:########:````:################################:```:##############:```
``:########:```````:#######################:````````````:#############:```
```:##########:````````:#####################:``` ` ```:############:```
``:############:``` `````:####################:```` ``:#############:``
```:##############:``` ``````:###################:``````:#############:``
```:###############:`` `````:####################:```:############:```
``:################:``` ````:##############################:``
``:##################:```` `````:##########################:```
``:####################:``` ` ```:#########################:```
``:######################:``` ````:#######################:``
```:#######################:```` `````:####################:```
```:##########################:``` ````:#################:```
``:#############################:``` ````:##############:```
``:##############################:```` `````:############:``
``:###########:``:###################:```` `````:#########:```
```:#########:`````:####################:``` ``:########:``
``:#######:``` ````:###################:```` ```:########:```
```:#######:``` ```:###################:```` ``:#########:```
```:#######:``` ````:###################:``` ``:##########:``
``:#########:``` ``````:###################:```` ` ```:##########:`` `
``:###########:`````````:######################:```````:###########:```
``:###############################################################:```
``:###############################################################:```
```:############################### #########:`` `
``:###############################: No-: Bling : DOTA mod :#########:```
````:############################## #########:` `
`````````````````````````:##:```:#############################:````:##:```
` ``` ```` ` ` ````````` ```````````````````````````````` ````")]
[assembly:AssemblyVersionAttribute("2020.07.08.2")] [assembly: AssemblyTitle("AveYo")]
namespace SteamDatabase.ValvePak
{
/*
VPKMOD Copyright (c) 2019 AveYo
Extending ValvePak library by SteamDatabase Team
MIT License
Copyright (c) 2016 Steam Database
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
internal static class StreamHelpers
{
public static string ReadNullTermString(this BinaryReader stream, Encoding encoding)
{
var characterSize = encoding.GetByteCount("e");
using (var ms = new MemoryStream())
{
while (true)
{
var data = new byte[characterSize];
stream.Read(data, 0, characterSize);
if (encoding.GetString(data, 0, characterSize) == "\0")
break;
ms.Write(data, 0, data.Length);
}
return encoding.GetString(ms.ToArray());
}
}
}
public static class Crc32
{
// CRC polynomial 0xEDB88320.
private static readonly uint[] Table =
{
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4,
0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,
0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A,
0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F,
0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950,
0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5,
0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6,
0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,
0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C,
0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31,
0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,
0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7,
0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8,
0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
};
public static uint Compute(byte[] buffer)
{
uint crc = 0xFFFFFFFF;
var bufferLength = buffer.Length;
for (var i = 0; i < bufferLength; i++)
{
crc = (crc >> 8) ^ Table[buffer[i] ^ (crc & 0xff)];
}
return ~crc;
}
}
public class ArchiveMD5SectionEntry
{
public uint ArchiveIndex { get; set; }
public uint Offset { get; set; }
public uint Length { get; set; }
public byte[] Checksum { get; set; }
}
public class PackageEntry
{
public string FileName { get; set; }
public string DirectoryName { get; set; }
public string TypeName { get; set; }
public uint CRC32 { get; set; }
public uint Length { get; set; }
public uint Offset { get; set; }
public ushort ArchiveIndex { get; set; }
public uint TotalLength { get { return SmallData == null ? Length : Length + (uint)SmallData.Length; } }
public byte[] SmallData { get; set; }
public string GetFileName()
{
return TypeName == " " ? FileName : FileName + "." + TypeName;
}
public string GetFullPath()
{
return DirectoryName == " " ? GetFileName() : DirectoryName + Package.DirectorySeparatorChar + GetFileName();
}
public override string ToString()
{
return String.Format("{0} crc=0x{1:x2} metadatasz={2} fnumber={3} ofs=0x{4:x2} sz={5}",
GetFullPath(), CRC32, SmallData.Length, ArchiveIndex, Offset, Length);
}
}
public class Package : IDisposable
{
/*
* Read() function was mostly taken from Rick's Gibbed.Valve.FileFormats,
* which is subject to this license:
*
* Copyright (c) 2008 Rick (rick 'at' gibbed 'dot' us)
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
public const int MAGIC = 0x55AA1234;
public const char DirectorySeparatorChar = '/';
private BinaryReader Reader;
private bool IsDirVPK;
private uint HeaderSize;
public string FileName { get; private set; }
public uint Version { get; private set; }
public uint TreeSize { get; private set; }
public uint FileDataSectionSize { get; private set; }
public uint ArchiveMD5SectionSize { get; private set; }
public uint OtherMD5SectionSize { get; private set; }
public uint SignatureSectionSize { get; private set; }
public byte[] TreeChecksum { get; private set; }
public byte[] ArchiveMD5EntriesChecksum { get; private set; }
public byte[] WholeFileChecksum { get; private set; }
public byte[] PublicKey { get; private set; }
public byte[] Signature { get; private set; }
public Dictionary<string,List<PackageEntry>> Entries { get; private set; }
public List<ArchiveMD5SectionEntry> ArchiveMD5Entries { get; private set; }
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing && Reader != null)
{
Reader.Dispose();
Reader = null;
}
}
public void SetFileName(string fileName)
{
if (fileName.EndsWith(".vpk", StringComparison.OrdinalIgnoreCase))
{
fileName = fileName.Substring(0, fileName.Length - 4);
}
if (fileName.EndsWith("_dir", StringComparison.OrdinalIgnoreCase))
{
IsDirVPK = true;
fileName = fileName.Substring(0, fileName.Length - 4);
}
FileName = fileName;
}
public void Read(string filename)
{
SetFileName(filename);
var fs = new FileStream(String.Format("{0}{1}.vpk", FileName, IsDirVPK ? "_dir" : ""),
FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
Read(fs);
}
public void Read(Stream input)
{
if (FileName == null)
throw new InvalidOperationException("You must call SetFileName() before calling Read() directly with a stream.");
Reader = new BinaryReader(input);
if (Reader.ReadUInt32() != MAGIC)
throw new InvalidDataException("Given file is not a VPK.");
Version = Reader.ReadUInt32();
TreeSize = Reader.ReadUInt32();
if (Version == 1)
{
// Nothing else
}
else if (Version == 2)
{
FileDataSectionSize = Reader.ReadUInt32();
ArchiveMD5SectionSize = Reader.ReadUInt32();
OtherMD5SectionSize = Reader.ReadUInt32();
SignatureSectionSize = Reader.ReadUInt32();
}
else
{
throw new InvalidDataException(String.Format("Bad VPK version. ({0})", Version));
}
HeaderSize = (uint)input.Position;
ReadEntries();
if (Version == 2)
{
// Skip over file data, if any
input.Position += FileDataSectionSize;
ReadArchiveMD5Section();
ReadOtherMD5Section();
ReadSignatureSection();
}
}
public PackageEntry FindEntry(string filePath)
{
if (filePath == null)
throw new ArgumentNullException("filePath");
filePath = filePath.Replace('\\', DirectorySeparatorChar);
var lastSeparator = filePath.LastIndexOf(DirectorySeparatorChar);
var directory = lastSeparator > -1 ? filePath.Substring(0, lastSeparator) : "";
var fileName = filePath.Substring(lastSeparator + 1);
return FindEntry(directory, fileName);
}
public PackageEntry FindEntry(string directory, string fileName)
{
if (directory == null)
throw new ArgumentNullException("directory");
if (fileName == null)
throw new ArgumentNullException("fileName");
var dot = fileName.LastIndexOf('.');
string extension;
if (dot > -1)
{
extension = fileName.Substring(dot + 1);
fileName = fileName.Substring(0, dot);
}
else
{
// Valve uses a space for missing extensions
extension = " ";
}
return FindEntry(directory, fileName, extension);
}
public PackageEntry FindEntry(string directory, string fileName, string extension)
{
if (directory == null)
throw new ArgumentNullException("directory");
if (fileName == null)
throw new ArgumentNullException("fileName");
if (extension == null)
throw new ArgumentNullException("extension");
if (!Entries.ContainsKey(extension))
return null;
// We normalize path separators when reading the file list
// And remove the trailing slash
directory = directory.Replace('\\', DirectorySeparatorChar).Trim(DirectorySeparatorChar);
// If the directory is empty after trimming, set it to a space to match Valve's behaviour
if (directory.Length == 0)
directory = " ";
return Entries[extension].Find(_ => _.DirectoryName == directory && _.FileName == fileName);
}
public void ReadEntry(PackageEntry entry, out byte[] output, bool validateCrc = true)
{
output = new byte[entry.SmallData.Length + entry.Length];
if (entry.SmallData.Length > 0)
entry.SmallData.CopyTo(output, 0);
if (entry.Length > 0)
{
Stream fs = null;
try
{
var offset = entry.Offset;
if (entry.ArchiveIndex != 0x7FFF)
{
if (!IsDirVPK)
throw new InvalidOperationException("Given VPK is not _dir, but entry references external archive.");
var fileName = String.Format("{0}_{1:d3}.vpk", FileName, entry.ArchiveIndex);
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
}
else
{
fs = Reader.BaseStream;
offset += HeaderSize + TreeSize;
}
fs.Seek(offset, SeekOrigin.Begin);
fs.Read(output, entry.SmallData.Length, (int)entry.Length);
}
finally
{
if (entry.ArchiveIndex != 0x7FFF && fs != null)
fs.Close();
}
}
if (validateCrc && entry.CRC32 != Crc32.Compute(output))
throw new InvalidDataException("CRC32 mismatch for read data.");
}
private void ReadEntries()
{
var typeEntries = new Dictionary<string, List<PackageEntry>>();
// Types
while (true)
{
var typeName = Reader.ReadNullTermString(Encoding.UTF8);
if (typeName == null || typeName.Length == 0)
break;
var entries = new List<PackageEntry>();
// Directories
while (true)
{
var directoryName = Reader.ReadNullTermString(Encoding.UTF8);
if (directoryName == null || directoryName.Length == 0)
break;
// Files
while (true)
{
var fileName = Reader.ReadNullTermString(Encoding.UTF8);
if (fileName == null || fileName.Length == 0)
break;
var entry = new PackageEntry
{
FileName = fileName,
DirectoryName = directoryName,
TypeName = typeName,
CRC32 = Reader.ReadUInt32(),
SmallData = new byte[Reader.ReadUInt16()],
ArchiveIndex = Reader.ReadUInt16(),
Offset = Reader.ReadUInt32(),
Length = Reader.ReadUInt32()
};
if (Reader.ReadUInt16() != 0xFFFF)
throw new FormatException("VPK entry with invalid terminator.");
if (entry.SmallData.Length > 0)
Reader.Read(entry.SmallData, 0, entry.SmallData.Length);
entries.Add(entry);
}
}
typeEntries.Add(typeName, entries);
}
Entries = typeEntries;
}
public void VerifyHashes()
{
if (Version != 2)
throw new InvalidDataException("Only version 2 is supported.");
using (var md5 = MD5.Create())
{
Reader.BaseStream.Position = 0;
var hash = md5.ComputeHash(
Reader.ReadBytes((int)(HeaderSize + TreeSize + FileDataSectionSize + ArchiveMD5SectionSize + 32)));
if (!hash.SequenceEqual(WholeFileChecksum))
throw new InvalidDataException(String.Format("Package checksum mismatch ({0} != expected {1})",
BitConverter.ToString(hash), BitConverter.ToString(WholeFileChecksum)));
Reader.BaseStream.Position = HeaderSize;
hash = md5.ComputeHash(Reader.ReadBytes((int)TreeSize));
if (!hash.SequenceEqual(TreeChecksum))
throw new InvalidDataException(String.Format("File tree checksum mismatch ({0} != expected {1})",
BitConverter.ToString(hash), BitConverter.ToString(TreeChecksum)));
Reader.BaseStream.Position = HeaderSize + TreeSize + FileDataSectionSize;
hash = md5.ComputeHash(Reader.ReadBytes((int)ArchiveMD5SectionSize));
if (!hash.SequenceEqual(ArchiveMD5EntriesChecksum))
throw new InvalidDataException(String.Format("Archive MD5 entries checksum mismatch ({0} != expected {1})",
BitConverter.ToString(hash), BitConverter.ToString(ArchiveMD5EntriesChecksum)));
// TODO: verify archive checksums
}
if (PublicKey == null || Signature == null)
return;
if (!IsSignatureValid())
throw new InvalidDataException("VPK signature is not valid.");
}
public bool IsSignatureValid()
{
// AveYo : just return true since RSA and AsnKeyParser are not used in VPKMOD
return true;
}
private void ReadArchiveMD5Section()
{
ArchiveMD5Entries = new List<ArchiveMD5SectionEntry>();
if (ArchiveMD5SectionSize == 0)
return;
var entries = ArchiveMD5SectionSize / 28; // 28 is sizeof(VPK_MD5SectionEntry), which is int + int + int + 16 chars
for (var i = 0; i < entries; i++)
{
ArchiveMD5Entries.Add(new ArchiveMD5SectionEntry
{
ArchiveIndex = Reader.ReadUInt32(),
Offset = Reader.ReadUInt32(),
Length = Reader.ReadUInt32(),
Checksum = Reader.ReadBytes(16)
});
}
}
private void ReadOtherMD5Section()
{
if (OtherMD5SectionSize != 48)
throw new InvalidDataException(String.Format("Encountered OtherMD5Section with size of {0} (should be 48)",
OtherMD5SectionSize));
TreeChecksum = Reader.ReadBytes(16);
ArchiveMD5EntriesChecksum = Reader.ReadBytes(16);
WholeFileChecksum = Reader.ReadBytes(16);
}
private void ReadSignatureSection()
{
if (SignatureSectionSize == 0)
return;
var publicKeySize = Reader.ReadInt32();
PublicKey = Reader.ReadBytes(publicKeySize);
var signatureSize = Reader.ReadInt32();
Signature = Reader.ReadBytes(signatureSize);
}
// AveYo: enhanced rework of my previous stand-alone vpk writer to fit in the Package class
public void SaveToFile(string fn)
{
// VPKMOD20 just counts offsets for duplicate files, so the exported .vpk is generally smaller for repetitive content!
var sw = Stopwatch.StartNew();
Directory.CreateDirectory(Path.GetDirectoryName(fn)); File.Delete(fn);
using (var sha1 = SHA1.Create())
using (FileStream fs = new FileStream(fn, FileMode.Create, FileAccess.Write))
using (MemoryStream mtree = new MemoryStream(), mdata = new MemoryStream())
using (BinaryWriter tree = new BinaryWriter(mtree), data = new BinaryWriter(mdata))
{
uint version = 1, tree_size = 0, data_offset = 0, lookup_offset = 0;
short preload_bytes = 0, archive_index = 0x7fff, terminator = -1;
byte zero = 0;
bool unique = true;
var seen = new Dictionary<string, uint>();
data.Write(0x4d4b5056); data.Write(0x3032444f); data_offset += 8; // ID
tree.Write(MAGIC); // Signature 4
tree.Write(version); // Version 4
tree.Write(tree_size); // TreeSize (TBD) 4
foreach (string etype in Entries.Keys)
{
tree.Write(Encoding.UTF8.GetBytes(etype)); // TypeName ?
tree.Write(zero); // 00 1
tree_size += (uint)etype.Length + 1;
var directories = Entries[etype].Select(_ => _.DirectoryName).Distinct();
foreach (string dirname in directories)
{
tree.Write(Encoding.UTF8.GetBytes(dirname)); // DirectoryName ?
tree.Write(zero); // 00 1
tree_size += (uint)dirname.Length + 1;
var files = Entries[etype].Where(_ => _.DirectoryName == dirname).Select(_ => _.FileName);
foreach (string filename in files)
{
byte[] data_bytes;
var found = Entries[etype].Find(_ => _.DirectoryName == dirname && _.FileName == filename);
if (found != null)
ReadEntry(found, out data_bytes, false); // it should always be found
else
data_bytes = new byte[0];
uint data_length = (uint)data_bytes.Length;
uint crc = Crc32.Compute(data_bytes);
string hash = String.Join("", sha1.ComputeHash(data_bytes));
if (seen.ContainsKey(hash))
{
unique = false; lookup_offset = seen[hash];
}
else
{
unique = true; lookup_offset = data_offset; seen.Add(hash, data_offset);
}
tree.Write(Encoding.UTF8.GetBytes(filename)); // FileName ?
tree.Write(zero); // 00 1
tree.Write(crc); // CheckSum 4
tree.Write(preload_bytes); // PreloadBytes 2
tree.Write(archive_index); // ArchiveIndex 2
tree.Write(lookup_offset); // EntryOffset 4
tree.Write(data_length); // EntryLength 4
tree.Write(terminator); // Terminator 2
if (unique)
{
data.Write(data_bytes); // DataBytes written
data_offset += data_length; // to secondary stream
}
tree_size += (uint)filename.Length + 19;
}
tree.Write(zero); // 00 Next Directory 1
tree_size += 1;
}
tree.Write(zero); // 00 Next Type 1
tree_size += 1;
}
tree.Write(zero); // 00 Tree End 1
tree_size += 1;
mtree.Position = 8; // TreeSize update
tree.Write(tree_size);
mtree.Position = 0; // Tree write
mtree.CopyTo(fs); // net 4.0
mdata.Position = 0; // Data write
mdata.CopyTo(fs);
}
sw.Stop();
Console.WriteLine(String.Format("--- Written {0} in {1}s", fn, sw.Elapsed.TotalSeconds));
}
public void AddEntry(string dir, string name, string ext, byte[] data)
{
if (Entries == null)
Entries = new Dictionary<string,List<PackageEntry>>();
if (!Entries.Keys.Contains(ext))
Entries.Add(ext, new List<PackageEntry>());
var found = Entries[ext].Find(_ => _.DirectoryName == dir && _.FileName == name);
if (found == null)
{
Entries[ext].Add(new PackageEntry {
FileName = name, DirectoryName = dir, TypeName = ext,
CRC32 = 0, SmallData = data, ArchiveIndex = 0, Offset = 0, Length = 0
});
}
else
{
found.Length = 0;
found.SmallData = data;
}
}
public void AddEntry(string fullpath, byte[] data)
{
var path = fullpath.Replace('\\', '/');
var s = path.LastIndexOf("/");
var dir = (s == -1) ? "" : path.Substring(0, s);
var file = path.Substring(s + 1);
s = file.LastIndexOf('.');
var ext = (s == -1) ? " " : file.Substring(s + 1);
var name = (s == -1) ? file : file.Substring(0, s);
if (Entries == null)
Entries = new Dictionary<string,List<PackageEntry>>();
if (!Entries.Keys.Contains(ext))
Entries.Add(ext, new List<PackageEntry>());
var found = Entries[ext].Find(_ => _.DirectoryName == dir && _.FileName == name);
if (found == null)
{
Entries[ext].Add(new PackageEntry {
FileName = name, DirectoryName = dir, TypeName = ext,
CRC32 = 0, SmallData = data, ArchiveIndex = 0, Offset = 0, Length = 0
});
}
else
{
found.Length = 0;
found.SmallData = data;
}
}
public void AddFolder(string inputdir)
{
// include pak01_dir subfolder (if it exists) for manual overrides when modding
if (!Directory.Exists(inputdir))
return;
var paths = new List<string>();
paths.AddRange(Directory.GetFiles(inputdir, "*.*", SearchOption.AllDirectories));
if (paths.Count == 0)
return;
Console.WriteLine("--- Adding files in \"{0}\"", inputdir);
var excluded = new List<string>() { "zip", "reg", "rar", "msi", "exe", "dll", "com", "cmd", "bat", "vbs" };
var iso = Encoding.GetEncoding("ISO-8859-1");
var utf = Encoding.UTF8;
foreach (var path in paths)
{
byte[] latin = Encoding.Convert(utf, iso, utf.GetBytes(path.Substring(inputdir.Length + 1)));
string root = iso.GetString(latin).ToLower();
var ext = Path.GetExtension(root).TrimStart('.');
if (excluded.Contains(ext))
continue; // ERROR illegal extension!
if (ext == "")
ext = " "; // WARNING missing extension
var name = Path.GetFileNameWithoutExtension(root);
if (name == "")
name = " "; // WARNING missing filename
var dir = Path.GetDirectoryName(root).Replace('\\', '/');
if (dir == "")
dir = " "; // WARNING missing directoryname
AddEntry(dir, name, ext, File.ReadAllBytes(path));
}
}
public void Filter(string types, string paths = null, string names = null)
{
var fTypes = String.IsNullOrEmpty(types) ? new List<string>() : types.Split(',').Select(_ => _.Trim()).ToList();
var fPaths = String.IsNullOrEmpty(paths) ? new List<string>() : paths.Split(',').Select(_ => _.Trim()).ToList();
var fNames = String.IsNullOrEmpty(names) ? new List<string>() : names.Split(',').Select(_ => _.Trim()).ToList();
foreach (string etype in Entries.Keys.ToList())
{
if (fTypes.Count > 0)
{
if (!fTypes.Contains(etype))
{
Entries.Remove(etype);
continue;
}
}
if (fPaths.Count > 0)
Entries[etype].RemoveAll(_ => !fPaths.Exists(_.DirectoryName.StartsWith));
if (fNames.Count > 0)
Entries[etype].RemoveAll(_ => !fNames.Exists(_.FileName.Equals));
}
}
}
}
namespace SteamKit.KeyValue
{
/*
VPKMOD Copyright (c) 2019 AveYo
Extending KeyValue library by SteamRE Team
LGPL License
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; version 2.1 of the License.
This library 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 Lesser General Public License for more details.
*/
public class KVTextReader : StreamReader
{
public static Dictionary<char,char> escapedMapping = new Dictionary<char,char>
{
{ '\\', '\\' }, { 'n', '\n' }, { 'r', '\r' }, //{ 't', '\t' },
};
public int lineNumber { get; private set; }
public KVTextReader(KV keyvalue, Stream input) : base(input)
{
bool wasQuoted;
bool wasConditional;
lineNumber = 1;
KV currentKey = keyvalue;
do
{
var s = ReadToken(out wasQuoted, out wasConditional);
if (String.IsNullOrEmpty(s))
break;
if (currentKey == null)
{
currentKey = new KV(s);
}
else
{
currentKey.k = s;
}
s = ReadToken(out wasQuoted, out wasConditional);
if (wasConditional)
{
//currentKey.condition = s;
// Now get the '{'
s = ReadToken(out wasQuoted, out wasConditional);
}
if (s != null && s.StartsWith("{") && !wasQuoted)
{
// header is valid so load the file
currentKey.RecursiveLoadFromBuffer(this);
}
else
{
throw new FormatException("KV: missing {");
}
currentKey = null;
}
while (!EndOfStream);
}
public void EatWhiteSpace()
{
while (!EndOfStream)
{
if (!Char.IsWhiteSpace((char)Peek()))
break;
if ((char)Read() == '\n')
lineNumber++;
}
}
public bool EatCPPComment()
{
if (!EndOfStream)
{
char next = (char)Peek();
if (next == '/')
{
ReadLine();
return true;
}
return false;
}
return false;
}
public string ReadToken(out bool wasQuoted, out bool wasConditional)
{
wasQuoted = false;
wasConditional = false;
while (true)
{
EatWhiteSpace();
if (EndOfStream)
return null;
if (!EatCPPComment())
break;
}
if (EndOfStream)
return null;
char next = (char)Peek();
if (next == '"')
{
wasQuoted = true;
// "
Read();
var sb = new StringBuilder();
while (!EndOfStream)
{
if (Peek() == '\\')
{
Read();
char escapedChar = (char)Read();
char replacedChar;
if (escapedMapping.TryGetValue(escapedChar, out replacedChar))
sb.Append(replacedChar);
else
sb.Append(escapedChar);
continue;
}
if (Peek() == '"')
break;
sb.Append((char)Read());
}
// "
Read();
return sb.ToString();
}
if (next == '{' || next == '}')
{
Read();
return next.ToString();
}
bool bConditionalStart = false;
int count = 0;
var ret = new StringBuilder();
while (!EndOfStream)
{
next = (char)Peek();
if (next == '"' || next == '{' || next == '}')
break;
if (next == '[')
bConditionalStart = true;
if (next == ']' && bConditionalStart)
wasConditional = true;
if (Char.IsWhiteSpace(next))
break;
if (count < 1023)
{
ret.Append(next);
}
else
{
throw new FormatException("KV: ReadToken overflow");
}
Read();
}
return ret.ToString();
}
}
public class KV
{
public KV(string name = null, string value = null, int index = 0)
{
this.k = name; this.v = value; this.i = index; this.items = new List<KV>();
}
public string k { get; set; }
public string v { get; set; }
public int i { get; private set; }
private static readonly KV empty = new KV();
private static readonly KV error = new KV();
public List<KV> items { get; private set; }
public List<KV>.Enumerator GetEnumerator() { return this.items.GetEnumerator(); }
public KV this[string key, int index = 0]
{
// index can be negative to return duplicates from the end ( -1 for last, -2 for second to last ... )
get
{
if (key == null || this.k == null)
{
return error; // prevent garbage values for non-existing key or index